<?php
/**
 * 俱乐部相关
 */
class paomeClubModel extends paomeBaseModel
{

    public function __construct(& $base)
    {
        parent::__construct($base);

        $this->table = 'r_pm_club';
    }

    /**
     * 俱乐部信息
     */
    public function getClubInfo($clubId,$fields='*') {
        return  $this->paomeDb->getRow("select $fields from r_pm_club where id=$clubId");
    }

    /**
     * 用户创建的正常俱乐部信息
     */
    public function getClubInfoByHeadUid($headUid,$fields='*') {
        return $this->paomeDb->getRow("select $fields from r_pm_club where head_uid=$headUid and status = 0");
    }

    /**
     * 用户当前所在的战队
     */
    public function getUserCurrentClubInfo($uid,$fields='*') {
        $sql = "select club_id from r_pm_club_users where uid= $uid and status=0";
        $info = $this->paomeDb->getRow($sql);
        if (!$info) return [];
        return $this->getClubInfo($info['club_id'],$fields);
    }

    /**
     * 查询俱乐部名称是否存在
     */
    public function getClubNameIsExist($name) {
        return $this->paomeDb->getOne("select id from r_pm_club where title ='$name'");
    }

    /**
     * 成员是否在战队里
     */
    public function getMemberIsInClub($uid) {
        return $this->paomeDb->getOne("select id from r_pm_club_users where uid=$uid  and status= 0");
    }

    /**
     *俱乐部列表
     */
    public function getClubList(array $params) {
        $paomeId = $params['paomeId'];
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $limitNum  = $params['limit'] ? (int)$params['limit'] : 10;
        $title     = isset($params['name']) ? trim($params['name']) : '';
        $status    = isset($params['status']) ? (int)$params['status'] : 0;
        $contestStatus    = isset($params['contestStatus']) ? (int)$params['contestStatus'] : 0;//赛季阶段
        $contestStatus2    = isset($params['contestStatus2']) ? (int)$params['contestStatus2'] : 0;//阶段状态
        $contestStatus3    = isset($params['contestStatus3']) ? (int)$params['contestStatus3'] : 0;//维度排序
        $userNumType    = isset($params['userNumType']) ? (int)$params['userNumType'] : 0; //俱乐部人数排序
        $where = 'b.contest_id='.$paomeId;
        if ($title) {
            $where .=' and a.title like '."'%$title%'";
        }
        if ($status) {
            if ($status == 1) {
                $status = 0;
            } else if($status == 5) {
                $status = -5;
            }
            $where .=' and a.status ='.$status;
        }

        if ($contestStatus) {
            $where .= ' and b.type = '.$contestStatus;
        }
        if ($contestStatus2) {
            switch($contestStatus2) {
                case 1:
                    $where .=' and b.status=15';//参与成功（竞赛中）
                    break;
                case 2:
                    $where .=' and b.status=0';//已报名（招募中）
                    break;
                case 3:
                    $where .=' and b.status in(5,10)';//已淘汰
                    break;
                case 4:
                    $where .=' and b.status = 20';//已结束
                    break;
                default:
                    break;
            }
        }

        $order = [];
        if ($contestStatus3) {
            switch($contestStatus3){
                case 1:
                    $order[]= 'b.mileage DESC';
                    break;
                case 2:
                    $order[] = 'b.speed DESC';
                    break;
                case 3:
                    $order[] = 'b.support_num DESC';
                    break;
                default:
                    break;
            }
        }
        if ($userNumType) {
            switch($userNumType){
                case 1:
                    $order[] = 'a.user_num DESC';
                    break;
                case 2:
                    $order[] = 'a.user_num ASC';
                    break;
                default:
                    break;
            }
        }
        if(count($order) == 0) {
            $order = ["b.type DESC","b.status DESC","a.create_time DESC"];
        } else {
            $order[] = 'a.create_time DESC';
        }
        $strOrder = implode(',',$order);
        $sql ="select a.id,a.title,a.image,a.status,a.create_time,a.user_num,
                      b.type AS bType,
                      b.status AS bStatus
                             FROM r_pm_club AS a
                             LEFT JOIN r_pm_club_status AS b ON a.id =b.club_id
                             WHERE $where
                             ORDER BY $strOrder
                             limit $start,$limitNum";
        $cntsql ="select count(1) as cnt FROM r_pm_club AS a
                             LEFT JOIN r_pm_club_status AS b ON a.id =b.club_id
                             WHERE $where";
        $this->total =  $this->paomeDb->getOne("$cntsql");
//        echo $sql;
        return $this->paomeDb->getAll($sql);
    }

    /**
     * 俱乐部详情
     */
    public function getClubDetail($paomeId,$clubId) {
        $where = 'a.id='.$clubId.' and b.contest_id='.$paomeId;
        $sql ="select a.id,a.title,a.image,a.status,a.create_time,a.user_num,
                      b.type AS bType,
                      b.status AS bStatus
                             FROM r_pm_club AS a
                             LEFT JOIN r_pm_club_status AS b ON a.id =b.club_id
                             WHERE $where";
       $info =  $this->paomeDb->getRow($sql);
        return $info;
    }

    /**
     *用户列表
     */
    public function getUserList2(array $params) {
        $paomeId = $params['paomeId'];
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $limitNum  = $params['limit'] ? (int)$params['limit'] : 10;
        $nickname     = isset($params['name']) ? trim($params['name']) : '';
        $clubame     = isset($params['clubName']) ? trim($params['clubName']) : '';
        $status    = isset($params['status']) ? (int)$params['status'] : 0;
        $contestStatus    = isset($params['contestStatus']) ? (int)$params['contestStatus'] : 0;//赛季阶段
        $contestStatus2    = isset($params['contestStatus2']) ? (int)$params['contestStatus2'] : 0;//阶段状态
        $contestStatus3    = isset($params['contestStatus3']) ? (int)$params['contestStatus3'] : 0;//维度排序
        $addTimeType    = isset($params['addTimeType']) ? (int)$params['addTimeType'] : 0; //加入时间排序
        $where = 'b.contest_id='.$paomeId;
        $this->total = 0;
        if($nickname){
            $searcher = $this->base->load('xunSearch')->init('user');
            $res = $searcher->result("$nickname",null,100000000,0);
            if (!$res) {
                return [];
            }
            $uid_in = [];
            foreach($res as $v){
                $uid_in[] = $v->uid;
            }
            $strUid = "('".implode("','",$uid_in)."')";
            $where .= ' and  a.uid in '.$strUid;
        }

        /*俱乐部昵称*/
        if ($clubame) {
           $list = $this->paomeDb->getAll("select id from r_pm_club where title like '%$clubame%'");
            if (!$list) {
                return [];
            }
            $arrClubId = [];
            foreach ($list as $key=>$val) {//优化 todo
                $arrClubId[] = $val['id'];
            }
            $strClubId = "('".implode("','",$arrClubId)."')";
            if ($contestStatus2) {
                $newWhere = 'contest_id='.$paomeId.' and club_id in'.$strClubId;
                switch($contestStatus2) {
                    case 1:
                        $newWhere .=' and status=15';//参与成功（竞赛中）
                        break;
                    case 2:
                        $newWhere .=' and status=0';//已报名（招募中）
                        break;
                    case 3:
                        $newWhere .=' and status in(5,10)';//已淘汰
                        break;
                    case 4:
                        $newWhere .=' and status = 20';//已结束
                        break;
                    default:
                        return [];
                        break;
                }
                $sql = "select club_id from r_pm_club_status where $newWhere";
                $arrClubList = $this->paomeDb->getAll($sql);
                if (!$arrClubList) {
                    return [];
                }
                $arrClubId = [];
                foreach ($arrClubList as $key=>$val) {//优化 todo
                    $arrClubId[] = $val['id'];
                }
                $strClubId = "('".implode("','",$arrClubId)."')";
            }
            $where .= ' and  a.club_id in '.$strClubId;
        } else if ($contestStatus2) {
            $newWhere = 'contest_id='.$paomeId;
            switch($contestStatus2) {
                case 1:
                    $newWhere .=' and status=15';//参与成功（竞赛中）
                    break;
                case 2:
                    $newWhere .=' and status=0';//已报名（招募中）
                    break;
                case 3:
                    $newWhere .=' and status in(5,10)';//已淘汰
                    break;
                case 4:
                    $newWhere .=' and status = 20';//已结束
                    break;
                default:
                    return [];
                    break;
            }

            $sql = "select club_id from r_pm_club_status where $newWhere";
            $arrClubList = $this->paomeDb->getAll($sql);
            if (!$arrClubList) {
                return [];
            }
            $arrClubId = [];
            foreach ($arrClubList as $key=>$val) {//优化 todo
                $arrClubId[] = $val['club_id'];
            }
            $strClubId = "('".implode("','",$arrClubId)."')";
            $where .= ' and  a.club_id in '.$strClubId;
        }

        if ($status) {
            if ($status == 1) $status = 0;
            $where .=' and a.status ='.$status;
        }

        if ($contestStatus) {
            $where .= ' and b.type = '.$contestStatus;
        }

        $order = [];
        if ($contestStatus3) {
            switch($contestStatus3){
                case 1:
                    $order[]= 'b.mileage DESC';
                    break;
                case 2:
                    $order[] = 'b.speed DESC';
                    break;
                case 3:
                    $order[] = 'b.support_num DESC';
                    break;
                case 4:
                    $order[] = 'b.max_mileage DESC';
                    break;
                default:
                    break;
            }
        }
        if ($addTimeType) {
            switch($addTimeType){
                case 1:
                    $order[] = 'a.create_time DESC';
                    break;
                case 2:
                    $order[] = 'a.create_time ASC';
                    break;
                default:
                    break;
            }
        }

        if (count($order) == 0) {
            $order = ["b.mileage DESC","a.create_time DESC"];
        }
        $strOrder = implode(',',$order);
        $sql ="select a.id,a.club_id,a.uid,a.status,a.create_time,a.level,
                      b.type AS bType,
                      b.mileage AS bmileage,
                      b.speed AS bSpeed,
                      b.support_num AS bSupportNum,
                      b.max_mileage AS bMaxMileage
                             FROM r_pm_club_users AS a
                             LEFT JOIN r_pm_users_status AS b ON a.club_id =b.club_id
                             WHERE $where
                             ORDER BY $strOrder
                             limit $start,$limitNum";
        $cntsql ="select count(1) as cnt FROM r_pm_club_users AS a
                             LEFT JOIN r_pm_users_status AS b ON a.club_id =b.club_id
                             WHERE $where";
        $this->total =  $this->paomeDb->getOne("$cntsql");
//        echo $sql;
        return $this->paomeDb->getAll($sql);
    }

    /**
     *用户列表----改 todo
     */
    public function getUserList(array $params) {
        $paomeId = $params['paomeId'];
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $limitNum  = $params['limit'] ? (int)$params['limit'] : 10;
        $nickname     = isset($params['name']) ? trim($params['name']) : '';
        $clubame     = isset($params['clubName']) ? trim($params['clubName']) : '';
        $status    = isset($params['status']) ? (int)$params['status'] : 0;
        $contestStatus    = isset($params['contestStatus']) ? (int)$params['contestStatus'] : 0;//赛季阶段
        //$contestStatus2    = isset($params['contestStatus2']) ? (int)$params['contestStatus2'] : 0;//阶段状态
        //暂去，后期优化 $contestStatus3    = isset($params['contestStatus3']) ? (int)$params['contestStatus3'] : 0;//维度排序
        $addTimeType    = isset($params['addTimeType']) ? (int)$params['addTimeType'] : 0; //加入时间排序
        $where = '1=1';
        $this->total = 0;
        if($nickname){
            $searcher = $this->base->load('xunSearch')->init('user');
            $res = $searcher->result("$nickname",null,100000000,0);
            if (!$res) {
                return [];
            }
            $uid_in = [];
            foreach($res as $v){
                $uid_in[] = $v->uid;
            }
            $strUid = "('".implode("','",$uid_in)."')";
            $where .= ' and  uid in '.$strUid;
        }

        /*俱乐部昵称*/
        if ($clubame) {
            $list = $this->paomeDb->getAll("select id from r_pm_club where title like '%$clubame%'");
            if (!$list) {
                return [];
            }
            $arrClubId = [];
            foreach ($list as $key=>$val) {//优化 todo
                $arrClubId[] = $val['id'];
            }
            $strClubId = "('" . implode("','", $arrClubId) . "')";
            $where .= ' and  club_id in ' . $strClubId;
        }
        $newWhere = '1=1';
        if ($contestStatus) {//赛季阶段,查询对应的俱乐部ID
            $newWhere .= ' and type=' . $contestStatus;
            if ($clubame) {
                $newWhere .= ' and  club_id in ' . $strClubId;
            }
            $sql = "select club_id from r_pm_club_status where $newWhere";
            $arrClubList = $this->paomeDb->getAll($sql);
            if (!$arrClubList) {
                return [];
            }
            $arrClubId = [];
            foreach ($arrClubList as $key => $val) {//优化 todo
                $arrClubId[] = $val['club_id'];
            }
            $strClubId = "('" . implode("','", $arrClubId) . "')";
            $where .= ' and  club_id in ' . $strClubId;
        }

        if ($status) {
            if ($status == 1) {
                $status = 0;
            } elseif($status == 2) {
               $status = -1;
            } else if($status == 5) {
               $status = -5;
            }
            $where .=' and status ='.$status;
        }
        $order = [];
        if ($addTimeType) {
            switch($addTimeType){
                case 1:
                    $order[] = 'create_time DESC';
                    break;
                case 2:
                    $order[] = 'create_time ASC';
                    break;
                default:
                    break;
            }
        }

        if (count($order) == 0) {
            $order = ["create_time DESC"];
        }
        $strOrder = implode(',',$order);
        $sql ="select id,club_id,uid,status,create_time,level
                             FROM r_pm_club_users
                             WHERE $where
                             ORDER BY $strOrder
                             limit $start,$limitNum";
        $cntsql ="select count(1) as cnt FROM r_pm_club_users
                             WHERE $where";
        $this->total =  $this->paomeDb->getOne("$cntsql");
//        echo $sql;
        return $this->paomeDb->getAll($sql);
    }

    /**
     * 参赛用户详情
     */
    public function getUserDetail($paomeId,$clubId,$uid) {
        $where = 'uid='.$uid.' and club_id='.$clubId;
        $sql ="select id,club_id,uid,status,create_time,level
                             FROM r_pm_club_users
                             WHERE $where";
        $info =  $this->paomeDb->getRow($sql);
        return $info;
    }


    /**
     * 俱乐部名称检测
     */
    public function checkClubName($name) {
        $len = mb_strlen($name, 'utf-8');
        if ($len < 1 || $len > 8) {
            return -1;//字数大于1  小于8
        }
        if($this->base->load('badwords')->check($name)){
            return -2;//存在违禁词
        }
        $isRepeat = $this->getClubNameIsExist($name);
        if ($isRepeat) {
            return -3;//重复昵称
        }
        return 1;
    }

    /**
     * 俱乐部介绍检测
     */
    public function checkClubContent($content) {
        $len = mb_strlen($content, 'utf-8');
        if ($len > 500) {
            return -1;//字数最多500
        }
        if($this->base->load('badwords')->check($content)){
            return -2;//存在违禁词
        }
        return 1;
    }

    /**
     * 当前阶段用户能否创建俱乐部
     * @param $uid
     * @return int   -1,-4:没有可用的赛季或当前不能创建俱乐部 -2 已经创建过俱乐部 -3：当前已加入其他俱乐部
     * （大于0都是正常的状态，返回的是创建完俱乐部，能参加的轮次） 1：第一轮 5 ：第二轮 10 第三轮 ……
     */
    public function getUserCanCreateClub($uid) {
         //当前的时间戳
        $nowTime = time();
        $sql = "select * from r_pm_rounds where start_time <= $nowTime and end_time >= $nowTime and status = 0  and type  limit 1";
        $info = $this->paomeDb->getRow($sql);
        if (!$info || in_array($info['type'],array(105,106)) || $info['type'] >=16) {//第一赛季 第二轮预赛之后不能创建战队（暂时手动处理）
             return -1;//没有可用的赛季,不能创建俱乐部
        }
        $isCreateClub = $this->isCreateClubForUid($uid);
        if ($isCreateClub) return -2;//创建了俱乐部
        $isAddClubForUid = $this->isAddClubForUid($uid);
        if ($isAddClubForUid) return -3;//加入了俱乐部
        $paomeId = $info['contest_id'];
        $sql = "SELECT `type` FROM `r_pm_rounds` where contest_id=$paomeId and `type`<105 and status=0 ORDER BY `type` desc limit 1;";
        $type = $this->paomeDb->getOne($sql);
        switch($type){
            case 12: //只有一轮
                if($info['type'] == 1) {
                    return 1;
                } else {
                    return -4;
                }
                break;
            case 22:
                if ($info['type'] == 1) {
                    return 1;
                } elseif (in_array($info['type'],array(5,6,10,11,12))) {
                      return 5;
                } else {
                  return -4;
                }
                break;
            case 32:
                if ($info['type'] == 1) {
                    return 1;
                } elseif (in_array($info['type'],array(5,6,10,11,12))) {
                    return 5;
                }else if (in_array($info['type'],array(15,16,20,21,22))) {
                    return 10;
                } else {
                    return -4;
                }
                break;
            default:
                return -4;
               break;
        }
    }


    /**
     * 用户是否创建过俱乐部，且俱乐部是正常状态
     */
    public function isCreateClubForUid($uid) {
        //用户是否创建过俱乐部，且俱乐部是正常状态
        $isRepeat = $this->paomeDb->getOne("select id from r_pm_club where head_uid=$uid and status=0");
        return $isRepeat ? $isRepeat : false;
    }

    /**
     * 查询用户是否加入了俱乐部
     */
    public function isAddClubForUid($uid) {
        $id = $this->paomeDb->getOne("select b.id from r_pm_club a
                                    LEFT JOIN  r_pm_club_users b ON a.id=b.club_id
                                    where b.uid=$uid and a.status=0 and b.status=0");
        return $id ? true : false;
    }

    /**
     *  创建俱乐部
     */
    public function addClub(array $params) {
        $data['provice_name'] = $params['proviceName'];
        $data['city_name'] =$params['cityName'];
        $data['title'] = $params['title'];
        $data['image'] = $params['image'];
        $data['content'] = $params['content'];
        $data['status'] = 0;
        $data['create_time'] = time();
        $data['head_uid'] = $params['uid'];
        $result = $this->paomeDb->insertRow('r_pm_club',$data,mysqldb::INSERT_COMMON);
        if (!$result) return false;
        //创建成员列表
        $result2 = $this->addClubUsers($params['uid'],$result,5);
        //更新赛事资格表
        $joinRoundsNum = $params['joinRoundsNum'];
        if (in_array($joinRoundsNum,array(1,5,10))) {
            //当前的时间戳
            $nowTime = time();
            $sql = "select * from r_pm_rounds where start_time <= $nowTime and end_time >= $nowTime and status = 0  and type  limit 1";
            $info = $this->paomeDb->getRow($sql);
            $paomeId = $info ? $info['contest_id'] : 0;
            if($paomeId) {
                $this->initCLubByAddClub($paomeId,$result,$joinRoundsNum);
            }
        }
        return $result;
    }

    /**
     * 申请加入
     */
    public function joinClub($uid, $clubId) {
        //当前的时间戳
        $nowTime = time();
        $sql = "select * from r_pm_rounds where start_time <= $nowTime and end_time >= $nowTime and status = 0    limit 1";
        $roundInfo = $this->paomeDb->getRow($sql);
        if (!$roundInfo) {
            return -5;//当前没有赛季
        }
        $sql = "select * from r_pm_contest where id= {$roundInfo['contest_id']}";
        $arrPaomeInfo = $this->paomeDb->getRow($sql);
        if (!$arrPaomeInfo) {
            return -5;//当前没有赛季
        }
        $existId = $this->paomeDb->getOne("select id from r_pm_club_users where uid=$uid and club_id<>$clubId and status =0");
        if ($existId) {
            return -4;//用户参与了其他俱乐部
        }
        $arrClubInfo = $this->getClubInfo($clubId, 'id,status,head_uid,user_num');
        if (!$arrClubInfo) {
            return -1;//俱乐部不存在
        }
        if ($arrClubInfo['status'] == -5) {
            return -2;//俱乐部已解散
        }
        $paomeId = $arrPaomeInfo['id'];
        //俱乐部不能变更的状态
        $arrStatus = common::$pmClubNumNotStatus;
        if (in_array($roundInfo['type'], $arrStatus)) {//俱乐部不能变更的状态
            $roundId2 = $this->base->load('paome/cup')->getRoundId($roundInfo['type'], 2);
            if ($roundId2) {
                //俱乐部赛季状态
                $isDoGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id=$paomeId and club_id=$clubId and `type`=$roundId2 and status in(15,20)");
                if ($isDoGame) {
                    return -6;//当前俱乐部正在冠军赛或争霸赛中,不能操作
                }
            }
        }
        //用户跟俱乐部是否已经存在关系
        $arrClubUser = $this->paomeDb->getRow("select id,status from r_pm_club_users where club_id=$clubId and uid=$uid");
        if ($arrClubUser && in_array($arrClubUser['status'], array(-1, 0))) {
            return -3;//重复申请加入
        }
        if ($arrClubInfo['user_num'] >= $arrPaomeInfo['max_num']) {
            return -7; //人数已达上限
        }
        if (isset($arrClubUser['id']) && $arrClubUser['status'] == -5) { //重新加入,待审核
            $result = $this->paomeDb->update("update r_pm_club_users set status=-1 where id={$arrClubUser['id']} and status=-5");
            //是否恢复个人跑量排名?? todo
        } else {
            $result = $this->addClubUsers($uid, $clubId, 0);
        }

        if ($result) {
            $messagePmModel = $this->base->load('paome/messagePm');
            //写入消息
            $mid = $messagePmModel->addPaomeMsg(array(
                'fromUid'=>$uid,
                'toUid'=>$arrClubInfo['head_uid'],
                'clubId'=>$clubId,
                'sourceId'=>$uid,//申请者
                'descType'=>'P1'
            ));
            //发消息
            if ($mid) {
//                $messagePmModel->sendMsg(array(
//                    'mid'=>$mid,
//                    'uid'=>$uid,
//                    'toUid'=>$arrClubInfo['head_uid'],
//                    'descType'=>'P1',
//                    'sourceId'=>$uid
//                ));
            }

        }
        return 1;
    }

    /**
     * 同意加入
     */
    public function agreeJoin($headUid, $mid) {
        //当前的时间戳
        $nowTime = time();
        $sql = "select * from r_pm_rounds where start_time <= $nowTime and end_time >= $nowTime and status = 0    limit 1";
        $roundInfo = $this->paomeDb->getRow($sql);
        if (!$roundInfo) {
            return -1;//当前没有赛季
        }
        $sql = "select * from r_pm_contest where id= {$roundInfo['contest_id']}";
        $arrPaomeInfo = $this->paomeDb->getRow($sql);
        if (!$arrPaomeInfo) {
            return -1;//当前没有赛季
        }
        //消息
        $arrMsg = $this->paomeDb->getRow("select * from r_pm_message where id=$mid and to_uid =$headUid and desc_type='P1'");
        if (!$arrMsg) {
            return -2;//当前消息不存在
        }
        if ($arrMsg['status'] <> 0) {
            return -3;//已处理过消息
        }
        $clubId = $arrMsg['club_id'];
        //历史的俱乐部是否正常
        $arrClubInfo = $this->getClubInfo($clubId, 'id,status,head_uid,user_num');
        if (!$arrClubInfo) {
            return -4;//俱乐部不存在
        }
        if ($arrClubInfo['status'] == -5) {
            return -5;//俱乐部已解散
        }
        if ($arrClubInfo['head_uid'] <> $headUid) {
           return -10;//非法操作，当前用户不是团长
        }
        $paomeId = $arrPaomeInfo['id'];
        //俱乐部不能变更的状态
        $arrStatus = common::$pmClubNumNotStatus;
        if (in_array($roundInfo['type'], $arrStatus)) {//俱乐部不能变更的状态
            $roundId2 = $this->base->load('paome/cup')->getRoundId($roundInfo['type'], 2);
            if ($roundId2) {
                //俱乐部赛季状态
                $isDoGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id=$paomeId and club_id=$clubId and `type`=$roundId2 and status in(15,20)");
                if ($isDoGame) {
                    return -6;//当前俱乐部正在冠军赛或争霸赛中,不能操作
                }
            }
        }

        //用户跟俱乐部是否已经存在关系
        $arrClubUser = $this->paomeDb->getRow("select id,status from r_pm_club_users where club_id=$clubId and uid={$arrMsg['from_uid']}");
        if (!$arrClubUser) {
            return -7;//加入失败，异常
        }
        //被加入者后来创建了战队
        if ($this->getUserCurrentClubInfo($arrMsg['from_uid'],'id')) {
            $this->killOtherRequest($arrMsg['from_uid']);
            return -11;//已加入其他俱乐部
        }
        if ($arrClubUser['status'] == -5) {
            $this->killOtherRequest($arrMsg['from_uid']);
            return -11;//已加入其他俱乐部
        }
        if ($arrClubUser['status'] == 0) {
            $this->killOtherRequest($arrMsg['from_uid']);
           return -8;//已经加入过该俱乐部
        }
        if ($arrClubInfo['user_num'] >= $arrPaomeInfo['max_num']) {
            return -9; //人数已达上限
        }




        $result = $this->modifyClubUsersStatus($arrClubUser['id'], $clubId, 1);
        if ($result) {
            $messagePmModel = $this->base->load('paome/messagePm');
            //同意消息状态变更
            $r2 = $messagePmModel->modifyPaomeMsg($mid, 5);
            if ($r2) {
                //写入消息
                $mid = $messagePmModel->addPaomeMsg(array(
                    'fromUid'=>$headUid,
                    'toUid'=>$arrMsg['from_uid'],
                    'clubId'=>$clubId,
                    'sourceId'=>$clubId,//俱乐部
                    'descType'=>'P3'
                ));
                //发消息
                if ($mid) {
//                    $messagePmModel->sendMsg(array(
//                        'mid'=>$mid,
//                        'uid'=>$headUid,
//                        'toUid'=>$arrMsg['from_uid'],
//                        'descType'=>'P3',
//                        'sourceId'=>$clubId
//                    ));
                }
            }
        }
        return 1;
    }

    /**
     * 退出俱乐部
     */
    public function outJoin($uid) {
        //当前的时间戳
        $nowTime = time();
        $sql = "select * from r_pm_rounds where start_time <= $nowTime and end_time >= $nowTime and status = 0    limit 1";
        $roundInfo = $this->paomeDb->getRow($sql);
        if (!$roundInfo) {
            return -1;//当前没有赛季
        }
        $sql = "select * from r_pm_contest where id= {$roundInfo['contest_id']}";
        $arrPaomeInfo = $this->paomeDb->getRow($sql);
        if (!$arrPaomeInfo) {
            return -1;//当前没有赛季
        }
        //查询用户俱乐部信息
        $arrClubInfo = $this->getUserCurrentClubInfo($uid,'id, status, head_uid, user_num');
        if (!$arrClubInfo) {
            return -3;//俱乐部不存在
        }
        if($arrClubInfo['status'] ==-5) {
            return -4;//俱乐部已解散
        }
        if ($arrClubInfo['head_uid'] == $uid) {
            return -5;//团长不能退出
        }
        $clubId = $arrClubInfo['id'];
        $paomeId = $arrPaomeInfo['id'];
        //俱乐部不能变更的状态
        $arrStatus = common::$pmClubNumNotStatus;
        $roundId2 = $this->base->load('paome/cup')->getRoundId($roundInfo['type'], 2);
        if (in_array($roundInfo['type'], $arrStatus)) {//俱乐部不能变更的状态
            if ($roundId2) {
                //俱乐部赛季状态
                $isDoGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id=$paomeId and club_id=$clubId and `type`=$roundId2 and status in(15,20)");
                if ($isDoGame) {
                    return -2;//当前俱乐部正在冠军赛或争霸赛中,不能操作
                }
            }
        }
        if ($this->base->load('paome/rank')->getClubIsHaveTicket($paomeId, $clubId)  && ($arrClubInfo['user_num'] <= $arrPaomeInfo['min_num']) ) {
            return -6;//有争霸赛资格,移除不能低于下限
        }
        //成员跟战队关系
        $arrClubUser = $this->paomeDb->getRow("select id,status from r_pm_club_users where club_id=$clubId and uid=$uid");
        if (!$arrClubUser || $arrClubUser['status']<>0) {//存在，加入状态--废除
            return -7;//失败，异常
        }
        $result = $this->modifyClubUsersStatus($arrClubUser['id'], $clubId, 2);//退出操作
        if ($result) {
            $roundId = $this->base->load('paome/cup')->getRoundId($roundInfo['type'], 1);
            if ($roundId && $roundId2) {//正常比赛阶段 全员排名删除才有意义
                //全员跑量排名删除
                $this->base->load('paome/rank')->delUserRank($paomeId, $uid, $clubId, $roundId, $roundId2);
            }

            $messagePmModel = $this->base->load('paome/messagePm');
            //写入消息 已退出您的战队
            $mid = $messagePmModel->addPaomeMsg(array(
                'fromUid'=>$uid,
                'toUid'=>$arrClubInfo['head_uid'],
                'clubId'=>$clubId,
                'sourceId'=>$uid,//用户
                'descType'=>'P2'
            ));
            //发消息
            if ($mid) {
//                $messagePmModel->sendMsg(array(
//                    'mid'=>$mid,
//                    'uid'=>$uid,
//                    'toUid'=>$arrClubInfo['head_uid'],
//                    'descType'=>'P2',
//                    'sourceId'=>$uid
//                ));
            }
        }
        return 1;
    }

    /**
     * 移除用户
     */
    public function outUsers($headUid, $toUid) {
        //当前的时间戳
        $nowTime = time();
        $sql = "select * from r_pm_rounds where start_time <= $nowTime and end_time >= $nowTime and status = 0    limit 1";
        $roundInfo = $this->paomeDb->getRow($sql);
        if (!$roundInfo) {
            return -1;//当前没有赛季
        }
        $sql = "select * from r_pm_contest where id= {$roundInfo['contest_id']}";
        $arrPaomeInfo = $this->paomeDb->getRow($sql);
        if (!$arrPaomeInfo) {
            return -1;//当前没有赛季
        }
        $paomeId = $arrPaomeInfo['id'];
        //俱乐部信息
        $arrClubInfo = $this->getClubInfoByHeadUid($headUid);
        if (!$arrClubInfo) {
          return -2;//战队不存在
        }

        //俱乐部不能变更的状态
        $arrStatus = common::$pmClubNumNotStatus;
        $roundId2 = $this->base->load('paome/cup')->getRoundId($roundInfo['type'], 2);
        if (in_array($roundInfo['type'], $arrStatus)) {//俱乐部不能变更的状态
            if ($roundId2) {
                //俱乐部赛季状态
                $isDoGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id=$paomeId and club_id={$arrClubInfo['id']} and `type`=$roundId2 and status in(15,20)");
                if ($isDoGame) {
                    return -3;//当前俱乐部正在冠军赛或争霸赛中,不能操作
                }
            }
        }

        if ($this->base->load('paome/rank')->getClubIsHaveTicket($paomeId, $arrClubInfo['id'])  && ($arrClubInfo['user_num'] <= $arrPaomeInfo['min_num']) ) {
            return -4;//有争霸赛资格,移除不能低于下限
        }

        //成员跟战队关系
        $arrClubUser = $this->paomeDb->getRow("select id,status from r_pm_club_users where club_id={$arrClubInfo['id']} and uid=$toUid");
        if (!$arrClubUser || $arrClubUser['status']<>0) {//存在，加入状态
            return -5;//失败，异常
        }
        $result = $this->modifyClubUsersStatus($arrClubUser['id'], $arrClubInfo['id'], 2);//移除操作
        if ($result) {
            $paomeStatus = $roundInfo['type'];
            $roundId = $this->base->load('paome/cup')->getRoundId($roundInfo['type'], 1);
            if ($roundId && $roundId2) {//正常比赛阶段 全员排名删除才有意义
                //全员跑量排名删除
                $this->base->load('paome/rank')->delUserRank($paomeId, $toUid, $arrClubInfo['id'], $roundId, $roundId2);
            }
            $messagePmModel = $this->base->load('paome/messagePm');
            //写入消息 您被移除战队
            $mid = $messagePmModel->addPaomeMsg(array(
                'fromUid'=>$headUid,
                'toUid'=>$toUid,
                'clubId'=>$arrClubInfo['id'],
                'sourceId'=>$arrClubInfo['id'],//用户
                'descType'=>'P4'
            ));
            //发消息
            if ($mid) {
//                $messagePmModel->sendMsg(array(
//                    'mid'=>$mid,
//                    'uid'=>$headUid,
//                    'toUid'=>$toUid,
//                    'descType'=>'P4',
//                    'sourceId'=>$arrClubInfo['id']
//                ));
            }
        }
        return 1;
    }

    /**
     * 解散俱乐部
     */
    public function killClub($headUid) {
        //当前的时间戳
        $nowTime = time();
        $sql = "select * from r_pm_rounds where start_time <= $nowTime and end_time >= $nowTime and status = 0    limit 1";
        $roundInfo = $this->paomeDb->getRow($sql);
        if (!$roundInfo) {
            return -1;//当前没有赛季
        }
        $sql = "select * from r_pm_contest where id= {$roundInfo['contest_id']}";
        $arrPaomeInfo = $this->paomeDb->getRow($sql);
        if (!$arrPaomeInfo) {
            return -1;//当前没有赛季
        }
        $arrClubInfo = $this->getClubInfoByHeadUid($headUid);
        if (!$arrClubInfo) {
           return -2;//俱乐部不存在
        }

        $clubId = $arrClubInfo['id'];
        $paomeId = $arrPaomeInfo['id'];
        //俱乐部不能解散的状态
        $arrStatus = common::$pmClubNotKillStatus;
        if (in_array($roundInfo['type'], $arrStatus)) {//俱乐部不能解散的状态
            $roundId2 = $this->base->load('paome/cup')->getRoundId($roundInfo['type'], 2);
            if ($roundId2) {
                //俱乐部赛季状态
                $isDoGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id=$paomeId and club_id=$clubId and `type`=$roundId2 and status in(15,20)");
                if ($isDoGame) {
                    return -3;//当前俱乐部正在冠军赛或争霸赛中,不能操作
                }
            }
        }

        if ($arrClubInfo['user_num'] >1) {
            return -4;//战队存在成员，不能解散
        }

        if ($this->base->load('paome/rank')->getClubIsHaveTicket($paomeId, $clubId) ) {
            return -5;//有争霸赛资格,不能解散(争霸赛资格用户数量不能低于5人，这种正常情况不会发生)
        }

        //成员跟战队关系
        $arrClubUser = $this->paomeDb->getRow("select id,status from r_pm_club_users where club_id=$clubId and uid=$headUid");
        if (!$arrClubUser || $arrClubUser['status']<>0) {//存在，加入状态(这种正常情况不会发生)
            return -6;//失败，异常
        }
        $result = $this->modifyClubUsersStatus($arrClubUser['id'], $clubId, 3);//解散操作
        if ($result) {
           $this->base->load("paome/paomeHall")->delClubRecomment($clubId);
        }
       //非比赛状态，删除排行榜无意义
        return 1;
    }

    /**
     * 战队报名下一轮
     */
    public function clubSignUpGame($headUid) {
        //当前赛季是否结束
         $info = $this->base->load('paome/cup')->getCurrentPaomeInfo();
        if (!$info) {
            return -1;//赛季不存在
        }
        $time = time();
        //查询当前赛季是否是最后一轮或争霸赛
        $arrRound = $this->paomeDb->getRow("select `type` from r_pm_rounds where $time >=start_time and $time <=end_time and status=0");
        if (!$arrRound || in_array($arrRound['type'],array(1,105,106))) {
            return -2;//当前不能报名下一轮
        }
        //检测战队
        $arrClubInfo = $this->getClubInfoByHeadUid($headUid);
        if (!$arrClubInfo) {
           return -3;//战队不存在
        }
        switch($arrRound['type']) {//当前赛季
//            case 1: //已存在的战队报名下一轮
//                break;
            case 5: //报名第二轮
            case 6:
                //当前战队是否在比赛中
                $isGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id ={$info['id']}  and club_id= {$arrClubInfo['id']} and type = 1 and status in(0,15,20)");
                if ($isGame)  {
                    return -2;
                }
                //查询是否报名了第二轮
            $isGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id ={$info['id']}  and club_id= {$arrClubInfo['id']} and type >= 10");
            if ($isGame)  {
                return -2;
            }
                $joinRoundsNum = 5;//第二轮
                $this-> initCLubByAddClubForSignUp($info['id'],$arrClubInfo['id'],$joinRoundsNum);
                 return 1;
            break;
            case 10:
            case 11:
                //当前战队是否在比赛中
                $isGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id ={$info['id']}  and club_id= {$arrClubInfo['id']} and type = 5 and status in(0,15,20)");
                if ($isGame)  {
                    return -2;
                }
                //查询是否报名了第二轮
                $isGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id ={$info['id']}  and club_id= {$arrClubInfo['id']} and type >=10");
                if ($isGame)  {
                    return -2;
                }
                $joinRoundsNum = 5;//第二轮
                $this-> initCLubByAddClubForSignUp($info['id'],$arrClubInfo['id'],$joinRoundsNum);
                return 1;
                break;
            case 12:
                //休赛
                //查询是否报名了第二轮
                $isGame = $this->paomeDb->getRow("select id from r_pm_club_status where contest_id ={$info['id']}  and club_id= {$arrClubInfo['id']} and type >=10");
                if ($isGame)  {
                    return -2;
                }
                $joinRoundsNum = 5;//第二轮
                $this-> initCLubByAddClubForSignUp($info['id'],$arrClubInfo['id'],$joinRoundsNum);
                return 1;
                break;
            default:
                return -2;
                break;
        }
    }


    /**
     * 创建俱乐部成员
     */
    public function addClubUsers($uid,$clubId,$isHeader=0) {
        $data['uid'] = $uid;
        $data['club_id'] = $clubId;
        $data['level'] = $isHeader ? 5: 0;
        $data['status'] = $isHeader ? 0: -1;
        $data['create_time'] = time();
        $result = $this->paomeDb->insertRow('r_pm_club_users',$data,mysqldb::INSERT_COMMON);
        if ($result && $isHeader) { //俱乐部成员数+1
             $this->paomeDb->update("update r_pm_club set user_num=user_num+1 where  id=$clubId ");
             $this->killOtherRequest($uid);
        }
        return $result;
    }

    /**
     * 成员状态变更
     */
    public function  modifyClubUsersStatus($id, $clubId, $type) {
        $result  = false;
        if ($type == 1) {//成员由待审核变为已加入
            $result = $this->paomeDb->update("update r_pm_club_users set status=0 where id= $id and status=-1");
            if ($result) {
                $uid = $this->paomeDb->getOne("select uid from r_pm_club_users where id=$id");
                $uid && $this->killOtherRequest($uid);
            }

        } else if($type == 2) {//成员退出/移除
            $time = time();
            $result = $this->paomeDb->update("update r_pm_club_users set status = -5 , exit_time=$time where id=$id and status=0");
            if ($result) {//退出流水
                $arr = $this->paomeDb->getRow("select uid,club_id from r_pm_club_users where id=$id");
                if ($arr) {
                    $data = [];
                    $data['club_id'] = $arr['club_id'];
                    $data['uid'] = $arr['uid'];
                    $data['create_time'] = time();
                    $data['exit_time'] = time();
                    $result = $this->paomeDb->insertRow('r_pm_club_user_time',$data,mysqldb::INSERT_COMMON);
                }
            }
        } else if($type == 3) { //解散俱乐部
            $result = $this->paomeDb->update("update r_pm_club set status = -5 where id=$clubId and status=0");
            $this->paomeDb->update("update r_pm_club_users set status = -5 where id=$id and status=0");
        }
        if ($result) {//人数统计
            $num = $this->paomeDb->getOne("select count(1) from r_pm_club_users where club_id=$clubId and status=0");;
            $this->paomeDb->update("update r_pm_club set user_num=$num where id= $clubId");
        }
        return $result;
    }

    /**
     * 加入其他俱乐部或者被其他俱乐部同意加入，删除请求
     */
    public function killOtherRequest($uid) {
        $this->paomeDb->update("update r_pm_club_users set status=-5 where uid= $uid and status=-1");  //其他待审核变为取消
        $this->paomeDb->update("update r_pm_message set status=-5 where from_uid=$uid and desc_type='P1' and status=0");
    }

    /**
     * 创建俱乐部时-初始化赛事资格表
     */
    public function initCLubByAddClub($paomeId,$clubId,$joinRoundsNum) {
        $arrStatus = array( //key:轮次ID  value:每轮预选赛ID
            1=>1,
            5=>10,
            10=>20
        );
        $roundId2 = $arrStatus[$joinRoundsNum];
        if (!$roundId2){
           return false;
        }
        $info = $this->paomeDb->getRow("select * from r_pm_club_status where contest_id=$paomeId and club_id=$clubId");
        if (!$info) {
            $data = [];
            $data['contest_id'] = $paomeId;
            $data['club_id'] = $clubId;
            $data['type'] = $roundId2;
            $data['status'] = 0;
            $data['create_time'] = time();
            $result = $this->paomeDb->insertRow('r_pm_club_status',$data,mysqldb::INSERT_COMMON);
        }

        $info = $this->paomeDb->getRow("select * from r_pm_club_status_list where contest_id=$paomeId and club_id=$clubId");
        if (!$info) {
            $data = [];
            $data['contest_id'] = $paomeId;
            $data['club_id'] = $clubId;
            $data['type'] = $roundId2;
            $data['status'] = 0;
            $data['create_time'] = time();
            $result = $this->paomeDb->insertRow('r_pm_club_status_list',$data,mysqldb::INSERT_COMMON);
        }

        $info = $this->paomeDb->getRow("select * from r_pm_club_rounds where contest_id=$paomeId and club_id=$clubId and `type`=$joinRoundsNum");
        if(!$info) {
            $data = [];
            $data['contest_id'] = $paomeId;
            $data['club_id'] = $clubId;
            $data['type'] = $joinRoundsNum;
            $data['create_time'] = time();
            $result = $this->paomeDb->insertRow('r_pm_club_rounds',$data,mysqldb::INSERT_COMMON);
        }
    }

    /**
     *报名下一轮初始化数据
     */
    public function initCLubByAddClubForSignUp($paomeId,$clubId,$joinRoundsNum) {
        $arrStatus = array( //key:轮次ID  value:每轮预选赛ID
            1=>1,
            5=>10,
            10=>20
        );
        $roundId2 = $arrStatus[$joinRoundsNum];
        if (!$roundId2){
            return false;
        }
        $info = $this->paomeDb->getRow("select * from r_pm_club_status where contest_id=$paomeId and club_id=$clubId");
        if (!$info) {
            $data = [];
            $data['contest_id'] = $paomeId;
            $data['club_id'] = $clubId;
            $data['type'] = $roundId2;
            $data['status'] = 0;
            $data['create_time'] = time();
            $result = $this->paomeDb->insertRow('r_pm_club_status',$data,mysqldb::INSERT_COMMON);
        } else if($joinRoundsNum == 5 && in_array($info['type'], array(1,5))) {   //目前只有2轮
              $data = [];
              $data['type'] = 10;
              $data['status'] = 0;
              $setStr = common::arrayToString($data);
                $sql = "update r_pm_club_status set $setStr where id= {$info['id']}";
                $this->paomeDb->update($sql);
        }else if($joinRoundsNum == 10 && in_array($info['type'], array(10,15))) {   //目前只有2轮
            $data = [];
            $data['type'] = 20;
            $data['status'] = 0;
            $setStr = common::arrayToString($data);
            $sql = "update r_pm_club_status set $setStr where id= {$info['id']}";
            $this->paomeDb->update($sql);
        }

        $info = $this->paomeDb->getRow("select * from r_pm_club_status_list where contest_id=$paomeId and club_id=$clubId and type= $roundId2");
        if (!$info) {
            $data = [];
            $data['contest_id'] = $paomeId;
            $data['club_id'] = $clubId;
            $data['type'] = $roundId2;
            $data['status'] = 0;
            $data['create_time'] = time();
            $result = $this->paomeDb->insertRow('r_pm_club_status_list',$data,mysqldb::INSERT_COMMON);
        }

        $info = $this->paomeDb->getRow("select * from r_pm_club_rounds where contest_id=$paomeId and club_id=$clubId and `type`=$joinRoundsNum");
        if(!$info) {
            $data = [];
            $data['contest_id'] = $paomeId;
            $data['club_id'] = $clubId;
            $data['type'] = $joinRoundsNum;
            $data['create_time'] = time();
            $result = $this->paomeDb->insertRow('r_pm_club_rounds',$data,mysqldb::INSERT_COMMON);
        }
    }


    /**
     * 增加淘汰战队记录
     */
    public function addClubOver(array $params) {
        $paomeId = $params['paomeId'];
        $clubId = $params['clubId'];
        $roundId2 = $params['roundId2'];
        $historyRank = $params['historyRank'];
        $mileage = $params['mileage'];;
        $info = $this->paomeDb->getRow("select * from r_pm_club_over where contest_id=$paomeId and club_id=$clubId and `type`=$roundId2");
        if(!$info) {
            $data['contest_id'] = $paomeId;
            $data['club_id'] = $clubId;
            $data['type'] = $roundId2;
            $data['history_rank'] = $historyRank;
            $data['mileage'] = $mileage;
            $data['create_time'] = time();
            $result = $this->paomeDb->insertRow('r_pm_club_over',$data,mysqldb::INSERT_COMMON);
        }
    }

    /**
     * 已经成功参与的俱乐部 是否淘汰
     */
    public function getIsExistOverClub($paomeId, $clubId, $roundId) {
        $where ="contest_id=$paomeId and club_id=$clubId";
        $where .=" and `type` =$roundId";
        $sql = "select * from r_pm_club_over where $where";
        return $this->paomeDb->getRow($sql);
    }

    /**
     * 查询淘汰俱乐部
     */
    public function getOverClubList($paomeId, $roundId=null, $roundId2=null) {
        $where = "contest_id=$paomeId";
        $arr = array(
            1=>[1,5],
            5=>[10,15],
            10=>[20,25]
        );
        if ($roundId && $arr[$roundId]) {
            $where .=" and type in(".implode(',',$arr[$roundId]).")";
        }
        if ($roundId2) {
            $where .=" and type = $roundId2";
        }

        $sql = "select club_id,history_rank,`type`,mileage from r_pm_club_over where $where ORDER BY `type` DESC,history_rank ASC ";
        $list = $this->paomeDb->getAll($sql);
        return $list;
    }

    /**
     * 战队列表
     * 预赛 未开始 进行中
     * 最后一轮决赛 显示 争霸赛战队列表
     */
    public function getClubListForApp2(array $params) {
        $start= (int)$params['start'];
        $offset= (int)$params['offset'];
        $uid= (int)$params['uid'];
        $clubName = $params['clubName'];
        $userNumOrder = $params['userNumOrder'];
        $statusOrder = $params['statusOrder'];
        $paomeId = $params['paomeId'];

        $where = "a.status=0 and a.user_num<30 and b.contest_id=$paomeId and  b.type in(1,10,20)";
        $whereZbs = "a.status=0 and a.user_num<30 and b.contest_id=$paomeId and  b.type in(1,10,20) and b.status in(0,15,20)";
        if ($statusOrder == 1) {//比赛未开始
            $where .= " and b.status=0";
        } elseif($statusOrder == 2) {//比赛进行中
            $where .= " and b.status in(15,20)";
        } else {
            $where .= " and b.status in(0,15,20)";
        }
        if ($clubName) {
           $where .= " and a.title like '%$clubName%'";
        }
        $order = 'a.user_num asc';//有少到多
        if ($userNumOrder == 1) {
            $order = 'a.user_num desc';//有多到少
        }
        $this->total = $this->paomeDb->getOne("select count(1) from r_pm_club as a
                left join r_pm_club_status as b ON a.id = b.club_id
                where $where");
        $list = [];
        if ($this->total) {
            $sql = "select a.*,b.type as bType,b.status as bStatus from r_pm_club as a
                left join r_pm_club_status as b ON a.id = b.club_id
                where $where
                order by $order limit $start,$offset";
            $list = $this->paomeDb->getAll($sql);
        } else {
            $totalOther = $this->paomeDb->getOne("select count(1) from r_pm_club as a
                left join r_pm_club_status as b ON a.id = b.club_id
                where $whereZbs");
            $arrPaome = $this->base->load('paome/cup')->getCurrentPaomeInfo('id,status');
            if (!$totalOther && $arrPaome && ($arrPaome['status'] <105) && $statusOrder<=1) {
                //查询争霸赛俱乐部
                $whereNew = "a.status=0 and a.user_num<30 and b.contest_id=$paomeId";
                if ($clubName) {
                    $whereNew .= " and a.title like '%$clubName%'";
                }
                $this->total =  $this->paomeDb->getOne("select count(1) from r_pm_champions_member where contest_id=$paomeId");
                if ($this->total) {
                      $list = $this->paomeDb->getAll("select a.*,b.id as topId from r_pm_club as a
                                                left join r_pm_champions_member as b on a.id=b.club_id
                                                where $whereNew order by $order limit $start,$offset");
                }
            }

        }
//        else {
//            //查询争霸赛俱乐部
//            $this->total =  $this->paomeDb->getOne("select count(1) from r_pm_champions_member where contest_id=$paomeId");
//            if ($this->total) {
//              $list = $this->paomeDb->getAll("select a.*,b.id as topId from r_pm_club as a
//                                        left join r_pm_champions_member as b on a.id=b.contest_id
//                                        where  b.contest_id=$paomeId limit $start,$offset");
//            }
//        }
        return $list;
    }

    /**
     * 战队列表
     * @param array $params
     * @return array
     */
    public function getClubListForApp(array $params) {
        $start= (int)$params['start'];
        $offset= (int)$params['offset'];
        $uid= (int)$params['uid'];
        $this->total = $this->paomeDb->getOne("select count(1) from r_pm_club where status = 0 and user_num<30");
        $list = [];
        if ($this->total) {
            $list = $this->paomeDb->getAll("select * from r_pm_club where status = 0 and user_num<30 order by user_num asc limit $start,$offset");
        }
        return $list;
    }

    /**
     * 战队列表
     */
    public function getClubUserListForApp(array $params) {
        $start= (int)$params['start'];
        $offset= (int)$params['offset'];
        $clubId= (int)$params['clubId'];
        $this->total = $this->paomeDb->getOne("select count(1) from r_pm_club_users where club_id= $clubId and status = 0 order by level desc");
        $list = [];
        if ($this->total) {
           // $list = $this->paomeDb->getAll("select * from r_pm_club_users where club_id= $clubId and status = 0  order by level desc limit $start,$offset");
            $list = $this->paomeDb->getAll("select * from r_pm_club_users where club_id= $clubId and status = 0  order by level desc");
        }
        return $list;
    }

    /**
     * 战队详情
     */
    public function getClubDetailApi2(array $params) {
        $clubId = $params['clubId'];
        $uid =$params['uid'];
        //用户是否参与
        $existId = $this->paomeDb->getOne("select id from r_pm_club_users where uid=$uid and club_id=$clubId and status =0");
        $result = array('doc'=>[],'homeData'=>[],'member'=>[]);
        /*doc资料 start*/
            $info = $this->getClubInfo($clubId);
            if (!$info) return $result;
        $doc = array(
                'id'=>$clubId,
                'title'=>$info['title'],
                'image'=>$info['image'] ? $info['image'].'?imageView2/2/w/128/h/128': '',
                'proviceName'=>$info['provice_name'],
                'cityName'=>$info['city_name'],
                'content'=>strip_tags(str_replace(array('\r\n', '\n', '\r'), '<br />', $info['content'])),
                'formatTime' => date('Y-m-d',$info['create_time']),
                'userNum'=>$info['user_num'],
                'isLeader' =>0,
                'userStatus' => 0//未加入
            );
            if ($uid) {
                $doc['isLeader'] = ($info['head_uid'] == $uid) ? 1 : 0;
                if ($info['head_uid'] == $uid) {
                    $doc['userStatus'] = 2;
                } else {
                    $sql = "select id,status from r_pm_club_users where uid= $uid and club_id={$info['id']} and status in(0,-1) ";
                    $arr = $this->paomeDb->getRow($sql);
                    if ($arr) {
                        if ($arr['status'] == 0) {
                            $doc['userStatus'] = 2;
                        } else { //待审核
                            $doc['userStatus'] = 1;
                        }
                    }
                }
            }
        $clubPmStatusMsg = '';//战队竞赛状态
        $paomeInfo = $this->base->load('paome/cup')->getCurrentPaomeInfo();
        $paomeId = $paomeInfo ? $paomeInfo['id'] : 0;
        $roundId = 0;
        $roundId2 = 0;
        if($paomeId) {
            $roundsDict = common::$roundsDict;
            foreach ($roundsDict as $k=>$v) {//主赛季
                if(in_array($paomeInfo['status'], $v)) {
                    $roundId = $k;
                    break;
                }
            }
            $arrRound2 = $this->paomeDb->getRow("select `type`,status from r_pm_club_status where contest_id=$paomeId and club_id=$clubId");
            if ($arrRound2) {
                $roundId2 = $arrRound2['type'];
                $clubPmStatusMsg = $this->getClubGameStatusMsg($paomeId, $paomeInfo['status'], $clubId, $roundId2, $arrRound2['status']);
                if($roundId == 1) { //下一轮未开始，阶段ID重新定义，回到上轮最后阶段
                    $roundId2 = $roundId2>5 ? 5: $roundId2;
                } else if($roundId == 5){
                    $roundId2 = $roundId2>15 ? 15: $roundId2;
                }else if($roundId == 10){
                    $roundId2 = $roundId2>25 ? 25: $roundId2;
                }else if($roundId == 100){
                    $roundId2 = 100;
                }
            }
        }
        $doc['clubPmStatusMsg'] = $clubPmStatusMsg;
        $doc['haveTicket'] = $this->base->load('paome/rank')->getClubIsHaveTicket($paomeId, $clubId);//争霸赛资格
        list($startTime, $endTime)  = $this->base->load('paome/cup')->getZbsTime($paomeId);
        $doc['zbsTime'] = array('startTime'=>$startTime, 'endTime'=>$endTime);//争霸赛时间
        $doc['haveCertificate'] =  $this->base->load('paome/center')->isCertificate($paomeId, $clubId);//是否有证书
       //赛季记录  冠军赛前10名都有奖杯（跑量）。争霸赛跑量 人气 配速都有奖杯....
        $arrGameLog = [];
        if ($paomeId) {
            $arrGameLog = $this->getClubGameLog($paomeId, $paomeInfo['status'], $clubId);
        }
        $doc['gameLog'] = $arrGameLog;
        /*doc资料 end*/

        /*homeData主页 start*/
         //1 战队数据
        $clubData = $this->getClubGameData($paomeId, $clubId, $roundId, $roundId2);
        $homeData['clubData'] = $clubData;
        //2 战队成员数据
        $totalUser = $this->paomeDb->getOne("select count(1) as cnt from r_pm_club_users where club_id=$clubId and status=0");
        $homeData['totalUser'] = $totalUser;
        if($roundId == 100) {
            $runData = $this->getUserRunLogNew($paomeId, $clubId, $roundId);
        } else {
            $runData = $this->getUserRunLog($paomeId, $clubId, $roundId);
        }
        $homeData['runData'] = $runData;
        $homeData['isClubUser'] = $existId ? 1 : 0;
        //chart图表--已参与才能看到
        if ($existId) {
            $homeData['chart'] = $this->getClubChart($paomeId, $roundId, $clubId);
        }
        /*homeData主页 end*/

        /*member成员 start*/
        $list = $this->paomeDb->getAll("select * from r_pm_club_users where club_id=$clubId and status = 0 order by level desc");
        $sortArr1 = [];
        $sortArr = [];
        $arrUserData = [];
        $userGameNum = 0;
        foreach ($list as $key=>$val) {
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'], 'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'], 'nickname');
            $arrUserData[$key]['uid'] = $val['uid'];
            $arrUserData[$key]['header'] = $header;
            $arrUserData[$key]['nickname'] = $nickname;
            $arrUserData[$key]['isLeader'] = ($val['level'] == 5) ? 1 : 0;
            $arrUserData[$key]['leaderIntroduce'] = '';
            if ($val['level'] == 5) {
                $arrUserData[$key]['leaderIntroduce'] = $this->paomeDb->getOne("select head_introduce from r_pm_club where id=$clubId");
            }
            $mile = 0;
            $arrUserData[$key]['mileage'] = $mile;
            if ($paomeId) {
                $mile = $this->paomeDb->getOne("select mileage from r_pm_users_rounds where contest_id=$paomeId and club_id=$clubId and `type`=$roundId and uid={$val['uid']}");
                $arrUserData[$key]['mileage'] = $mile ? $mile : 0;
                if ($arrUserData[$key]['mileage'] > 0) {
                    $userGameNum++;
                }
            }
            $sortArr[] = $mile;
            $sortArr1[] = $val['level'];
        }
        array_multisort($sortArr1, SORT_DESC, $sortArr, SORT_DESC, $arrUserData);
        $member['memberList']= array('gameNum'=>$userGameNum,'list'=>$arrUserData);
        /*member成员 end*/
        if ($roundId <> 100) {
            $member['star'] = $this->getClubMemberList($paomeId, $roundId, $clubId);
        }
      return array('doc'=>$doc, 'homeData'=>$homeData, 'member'=>$member);
    }

    /**
     * 查询战队竞赛状态--俱乐部详情 -app 标题文字
     * $paomeId 赛季ID
     * $status 赛季状态 r_pm_contest 的 status
     * $clubId 战队ID
     * $roundId2 赛季轮次ID r_pm_club_status 的 type
     * $roundStatus2  赛季轮次状态 r_pm_club_status 的status
     */
    public function getClubGameStatusMsg($paomeId, $status, $clubId, $roundId2, $roundStatus2) {
        $content = '';
        //$arr = $this->paomeDb->getRow("select `type`,status from r_pm_club_status where contest_id=$paomeId and club_id=$clubId");
        $arr = array('type'=>$roundId2, 'status'=>$roundStatus2);
        if (in_array($arr['status'],array(5,10))) {
             return $content;
        }
        switch($arr['type']) {
            case 1:
                switch ($arr['status']) {
                    case 0://报名
                        $content = '第一轮招募中';
                        break;
                    case 15:
                    case 20:
                    $content = '第一轮预选赛进行中';
                    break;
                }
                break;
            case 5:
                switch ($arr['status']) {
                    case 15:
                        $content = '第一轮冠军赛进行中';
                        break;
                    case 20:
                         //空档期显示：预选/冠军赛进行中
                         //取得争霸赛资格显示：休赛期
                         //其他：空
                        if(!$status) return '';
                        if ($status == 11) {
                            $content = '第一轮冠军赛进行中';
                        } else if($status == 12){
                            $bool = $this->base->load('paome/rank')->getClubIsHaveTicket($paomeId, $clubId);
                            if ($bool === true) {
                                $content = '第一轮休赛中';
                            }
                        }
                        break;
                }
                break;
            case 10:
                switch ($arr['status']) {
                    case 0://报名
                        $content = '第二轮招募中';
                        break;
                    case 15:
                    case 20:
                        $content = '第二轮预选赛进行中';
                        break;
                }
                break;
            case 15:
                switch ($arr['status']) {
                    case 15:
                        $content = '第二轮冠军赛进行中';
                        break;
                    case 20:
                        //空档期显示：预选/冠军赛进行中
                        //取得争霸赛资格显示：休赛期
                        //其他：空
                        if(!$status) return '';
                        if ($status == 21) {
                            $content = '第二轮冠军赛进行中';
                        } else if($status == 22){
                            $bool = $this->base->load('paome/rank')->getClubIsHaveTicket($paomeId, $clubId);
                            if ($bool === true) {
                                $content = '第二轮休赛中';
                            }
                        }
                        break;
                }
                break;
            case 20:
                switch ($arr['status']) {
                    case 0://报名
                        $content = '第三轮招募中';
                        break;
                    case 15:
                    case 20:
                        $content = '第三轮预选赛进行中';
                        break;
                }
                break;
            case 25:
                switch ($arr['status']) {
                    case 15:
                        $content = '第三轮冠军赛进行中';
                        break;
                    case 20:
                        //空档期显示：预选/冠军赛进行中
                        //取得争霸赛资格显示：休赛期
                        //其他：空
                        if(!$status) return '';
                        if ($status == 31) {
                            $content = '第三轮冠军赛进行中';
                        } else if($status == 32){
                            $bool = $this->base->load('paome/rank')->getClubIsHaveTicket($paomeId, $clubId);
                            if ($bool === true) {
                                $content = '第三轮休赛中';
                            }
                        }
                        break;
                }
                break;
            case 100:
                 if (in_array($status,array(105,106))){
                     $content = '冠军争霸赛';
                 } else if($status == 120) {
                     $content = '冠军争霸赛已结束';
                 }
                break;
            default:
                break;
        }
        return $content;
    }

    /**
     * 战队赛季记录
     * 比赛结果没出来，数据不呈现
     * $paomeId 赛季ID
     * $status 赛季状态 r_pm_contest 的 status
     * $clubId 战队Id
     */
    public function getClubGameLog($paomeId, $status, $clubId) {
        //查询赛季轮次列表记录
        $list =$this->paomeDb->getAll("select `type`,status from r_pm_club_status_list where contest_id = $paomeId and club_id = $clubId and status<> 0 order by `type` desc");
        if (!$list) {
            return [];
        }
        $result = [];
        foreach ($list as $key=>$val) {
            switch($val['type']) {
                case 100:
                    if($status == 120) {
                        $roundId = 100;//轮次
                        $gameLog = array(
                            'headMsg'=>'冠军争霸赛',
                            'list'=>[],
                            'tips'=>''
                        );
                        $info = $this->paomeDb->getRow("select id,score_rank_num,total_score,mileage_score,speed_score,support_score from r_pm_score where contest_id=$paomeId and club_id= $clubId and `type`=$roundId");
                        $total = $this->paomeDb->getOne("select count(1) from r_pm_score where contest_id=$paomeId and `type`=$roundId and score_rank_num>0");
                        $child[] = array(
                            'childMsg'=>'总积分',
                            'type'=>4,
                            'rankValue'=>$info ? $info['total_score'] : 0,
                            'rank'=> $info ? $info['score_rank_num'] : 0,
                            'num'=>$total,//总数
                            'haveCup'=>1,
                            'mileageScore'=>$info ? $info['mileage_score'] : 0,
                            'speedScore'=>$info ? $info['speed_score'] : 0,
                            'supportScore'=> $info ? $info['support_score'] : 0,
                        );
                        $gameLog['list'] = $child;
                        $result[] = $gameLog;
                    }
                    break;
                case 25: //第三轮决赛
                         if(in_array($val['status'],array(15, 20))) { //进行中 | 已结束 ，1：真的结束了 2：空档期
                             $gameLog = array(
                                 'headMsg'=>'第三轮最好成绩',
                                 'list'=>[],
                                 'tips'=>''
                             );
                              if ($status >= 32) {//第三轮休赛期 真的结束了
                                  $roundId = 10;//轮次
                                  //查询排名
                                  $rankClubKeyMile = 'rankClub-mileage-'.$paomeId.'-'.$roundId;
                                  $rankMile = ($this->redis->zRevRank($rankClubKeyMile, $clubId)!==false) ? ($this->redis->zRevRank($rankClubKeyMile, $clubId))+1 : false;
                                  $rankClubKeyMileOk = 'rankClub-mileageOk-'.$paomeId.'-'.$roundId;
                                  $rankMileOk = ($this->redis->zRevRank($rankClubKeyMileOk, $clubId)!==false) ? ($this->redis->zRevRank($rankClubKeyMileOk, $clubId))+1 : false;
                                  if(!$rankMile) {
                                      //$result[] = $gameLog;
                                      continue;
                                  }
                                  $child = [];
                                  if ($rankMile) {
                                      $child[] = array(
                                          'childMsg'=>'冠军赛总跑量'.(($rankMile == 1) ? '冠军': '成绩'),
                                          'type'=>1,
                                          'rankValue'=>(double)$this->redis->zScore($rankClubKeyMile, $clubId),
                                          'rank'=>$rankMile,
                                          'num'=>$this->redis->zSize($rankClubKeyMile),//总数
                                          'haveCup'=>$rankMileOk ?($rankMileOk <=10 ? 1 : 0) : 0
                                      );
                                  }
                                  $gameLog['list'] = $child;
                              } else {
                                  $gameLog['tips'] = '第三轮跑量冠军赛成绩即将公布'; //进行中 | 2：空档期
                              }
                             $result[] = $gameLog;
                         }
                    break;
                case 20://第三轮预选赛
                    if (in_array($val['status'],array(10))) {//5人数未满下限 10未能晋级冠军赛
                        $roundId = 10;//轮次
                        $roundId2 = 20;//阶段
                        $gameLog = array(
                            'headMsg'=>'第三轮最好成绩',
                            'list'=>[],
                            'tips'=>''
                        );
                        //查询排名
                        $rankClubJdKeyMile= 'rankClubJd-mileage-'.$paomeId.'-'.$roundId.'-'.$roundId2;//阶段
                        $rankMile = ($this->redis->zRevRank($rankClubJdKeyMile, $clubId)!==false) ? ($this->redis->zRevRank($rankClubJdKeyMile, $clubId))+1 : false;
                        if(!$rankMile) {
                            continue;
                        }
                        $child = [];
                        if ($rankMile) {
                            $child[] = array(
                                'childMsg'=>'预选赛总跑量成绩',
                                'type'=>1,
                                'rankValue'=>(double)$this->redis->zScore($rankClubJdKeyMile, $clubId),
                                'rank'=>$rankMile,
                                'num'=>$this->redis->zSize($rankClubJdKeyMile),//总数
                                'haveCup'=>0
                            );
                        }
                        $gameLog['list'] = $child;
                        $result[] = $gameLog;
                    }
                    break;
                case 15: //第二轮决赛
                    if(in_array($val['status'],array(15, 20))) { //进行中 | 已结束 ，1：真的结束了 2：空档期
                        $gameLog = array(
                            'headMsg'=>'第二轮最好成绩',
                            'list'=>[],
                            'tips'=>''
                        );
                        if ($status >= 22) {//第三轮休赛期 真的结束了
                            $roundId = 5;//轮次: 第二轮
                            //查询排名
                            $rankClubKeyMile = 'rankClub-mileage-'.$paomeId.'-'.$roundId;
                            $rankMile = ($this->redis->zRevRank($rankClubKeyMile, $clubId)!==false) ? ($this->redis->zRevRank($rankClubKeyMile, $clubId))+1 : false;
                            $rankClubKeyMileOk = 'rankClub-mileageOk-'.$paomeId.'-'.$roundId;
                            $rankMileOk = ($this->redis->zRevRank($rankClubKeyMileOk, $clubId)!==false) ? ($this->redis->zRevRank($rankClubKeyMileOk, $clubId))+1 : false;
                            if(!$rankMile) {
                                //$result[] = $gameLog;
                                continue;
                            }
                            $child = [];
                            if ($rankMile) {
                                $child[] = array(
                                    'childMsg'=>'冠军赛总跑量'.(($rankMile == 1) ? '冠军': '成绩'),
                                    'type'=>1,
                                    'rankValue'=>(double)$this->redis->zScore($rankClubKeyMile, $clubId),
                                    'rank'=>$rankMile,
                                    'num'=>$this->redis->zSize($rankClubKeyMile),//总数
                                    'haveCup'=>$rankMileOk ?($rankMileOk <=10 ? 1 : 0) : 0
                                );
                            }
                            $gameLog['list'] = $child;
                        } else {
                            $gameLog['tips'] = '第二轮跑量冠军赛成绩即将公布'; //进行中 | 2：空档期
                        }
                        $result[] = $gameLog;
                    }
                    break;
                case 10://第二轮预选赛
                    if (in_array($val['status'],array(10))) {//5人数未满下限 10未能晋级冠军赛
                        $roundId = 5;//轮次
                        $roundId2 = 10;//阶段
                        $gameLog = array(
                            'headMsg'=>'第二轮最好成绩',
                            'list'=>[],
                            'tips'=>''
                        );
                        //查询排名
                        $rankClubJdKeyMile= 'rankClubJd-mileage-'.$paomeId.'-'.$roundId.'-'.$roundId2;//阶段
                        $rankMile = ($this->redis->zRevRank($rankClubJdKeyMile, $clubId)!==false) ? ($this->redis->zRevRank($rankClubJdKeyMile, $clubId))+1 : false;
                        if(!$rankMile) {
                            continue;
                        }
                        $child = [];
                        if ($rankMile) {
                            $child[] = array(
                                'childMsg'=>'预选赛总跑量成绩',
                                'type'=>1,
                                'rankValue'=>(double)$this->redis->zScore($rankClubJdKeyMile, $clubId),
                                'rank'=>$rankMile,
                                'num'=>$this->redis->zSize($rankClubJdKeyMile),//总数
                                'haveCup'=>0
                            );
                        }
                        $gameLog['list'] = $child;
                        $result[] = $gameLog;
                    }
                    break;
                case 5: //第三轮
                    if(in_array($val['status'],array(15, 20))) { //进行中 | 已结束 ，1：真的结束了 2：空档期
                        $gameLog = array(
                            'headMsg'=>'第一轮最好成绩',
                            'list'=>[],
                            'tips'=>''
                        );
                        if ($status >= 12) {//第三轮休赛期 真的结束了
                            $roundId = 1;//轮次
                            //查询排名
                            $rankClubKeyMile = 'rankClub-mileage-'.$paomeId.'-'.$roundId;
                            $rankMile = ($this->redis->zRevRank($rankClubKeyMile, $clubId)!==false) ? ($this->redis->zRevRank($rankClubKeyMile, $clubId))+1 : false;
                            $rankClubKeyMileOk = 'rankClub-mileageOk-'.$paomeId.'-'.$roundId;
                            $rankMileOk = ($this->redis->zRevRank($rankClubKeyMileOk, $clubId)!==false) ? ($this->redis->zRevRank($rankClubKeyMileOk, $clubId))+1 : false;
                            if(!$rankMile) {
                               // $result[] = $gameLog;
                                continue;
                            }
                            $child = [];
                            if ($rankMile) {
                                $child[] = array(
                                    'childMsg'=>'冠军赛总跑量'.(($rankMile == 1) ? '冠军': '成绩'),
                                    'type'=>1,
                                    'rankValue'=>(double)$this->redis->zScore($rankClubKeyMile, $clubId),
                                    'rank'=>$rankMile,
                                    'num'=>$this->redis->zSize($rankClubKeyMile),//总数
                                    'haveCup'=>$rankMileOk ?($rankMileOk <=10 ? 1 : 0) : 0
                                );
                            }
                            $gameLog['list'] = $child;
                        } else {
                            $gameLog['tips'] = '第一轮跑量冠军赛成绩即将公布'; //进行中 | 2：空档期
                        }
                        $result[] = $gameLog;
                    }
                    break;
                case 1://第三轮预选赛
                    if (in_array($val['status'],array(10))) {//10未能晋级冠军赛
                        $roundId = 1;//轮次
                        $roundId2 = 1;//阶段
                        $gameLog = array(
                            'headMsg'=>'第一轮最好成绩',
                            'list'=>[],
                            'tips'=>''
                        );
                        //查询排名
                        $rankClubJdKeyMile= 'rankClubJd-mileage-'.$paomeId.'-'.$roundId.'-'.$roundId2;//阶段
                        $rankMile = ($this->redis->zRevRank($rankClubJdKeyMile, $clubId)!==false) ? ($this->redis->zRevRank($rankClubJdKeyMile, $clubId))+1 : false;
                        if(!$rankMile) {
                            continue;
                        }
                        $child = [];
                        if ($rankMile) {
                            $child[] = array(
                                'childMsg'=>'预选赛总跑量成绩',
                                'rankValue'=>(double)$this->redis->zScore($rankClubJdKeyMile, $clubId),
                                'type'=>1,
                                'rank'=>$rankMile,
                                'num'=>$this->redis->zSize($rankClubJdKeyMile),//总数
                                'haveCup'=>0
                            );
                        }
                        $gameLog['list'] = $child;
                        $result[] = $gameLog;
                    }
                    break;
            }
        }
        return $result;
    }

    /**
     * 战队详情 -主页 - 竞赛数据
     * $paomeId 赛季ID
     * $status 赛季状态 r_pm_contest 的 status
     * $clubId 战队ID
     * $roundId2 赛季轮次ID r_pm_club_status 的 type
     * $roundStatus2  赛季轮次状态 r_pm_club_status 的status
     */
    public function getClubGameData($paomeId, $clubId, $roundId, $roundId2) {
        $gameTitle = array(
            'type'=>0,
            'title'=>'竞赛数据'
        );
        $mileGameData = array('type'=>1,'rank'=>0,'rankValue'=>0,'num'=>0);//里程
        $speedGameData = array('type'=>2,'rank'=>0,'rankValue'=>common::sec3format(0),'num'=>0);//配速
        $supportGameData = array('type'=>3,'rank'=>0,'rankValue'=>0,'num'=>0);//人气
        $gameData = array($mileGameData, $speedGameData, $supportGameData);
        $result = array('gameTitle'=>$gameTitle,'gameData'=>$gameData);

        $arrStatusMsg =  common::$arrStatusMsg;
        $result['gameTitle']['type'] = $roundId2;//轮次阶段
        $result['gameTitle']['title'] = isset($arrStatusMsg[$roundId2]) ? '战队'.$arrStatusMsg[$roundId2].'数据' : '竞赛数据';
        if ($roundId == 100) {
            //查询争霸日期
            $arrDate = $this->base->load('paome/cup')->getDateList($paomeId, $roundId);
            if ($arrDate) {
                //查询主框显示的日期
                $date = $this->base->load('paome/cup')->getLastDate($arrDate); //当前显示的格式化日期值
                $nowTime = strtotime($date);//当前显示的日期时间戳
                $total = $this->paomeDb->getOne("select count(1) from r_pm_score where contest_id=$paomeId and `type`=$roundId and score_rank_num>0");

                $rankNum = $this->base->load('paome/rank')->getObjectDayRank($clubId, $paomeId, $roundId, $date, 1);
                $rankValue = $this->base->load('paome/rank')->getObjectDayRankValue($clubId, $paomeId, $roundId, $date, 1);

                $mileGameData = array(
                    'type'=>1,
                    'rank'=>$rankNum,
                    'rankValue'=>$rankValue,
                    'num'=>$total,
                    'score'=>$this->base->load('paome/rank')->getClubRankScore((int)$rankNum, 1)
                );//里程
                $rankNum = $this->base->load('paome/rank')->getObjectDayRank($clubId, $paomeId, $roundId, $date, 5);
                $rankValue = $this->base->load('paome/rank')->getObjectDayRankValue($clubId, $paomeId, $roundId, $date, 5);
                $speedGameData = array(
                    'type'=>2,
                    'rank'=>$rankNum,
                    'rankValue'=>$rankValue,
                    'num'=>$total,
                    'score'=>$this->base->load('paome/rank')->getClubRankScore((int)$rankNum, 5)
                );//配速
                $rankNum = $this->base->load('paome/rank')->getObjectDayRank($clubId, $paomeId, $roundId, $date, 10);
                $rankValue = $this->base->load('paome/rank')->getObjectDayRankValue($clubId, $paomeId, $roundId, $date, 10);
                $supportGameData = array(
                    'type'=>3,
                    'rank'=>$rankNum,
                    'rankValue'=>$rankValue,
                    'num'=>$total,
                    'score'=>$this->base->load('paome/rank')->getClubRankScore((int)$rankNum, 10)
                );//人气
            }
        } else {
            $rankClubJdKeyMile     = 'rankClubJd-mileage-'.$paomeId.'-'.$roundId.'-'.$roundId2;//阶段
            $rankClubKeySpeed      = 'rankClub-speed-'.$paomeId.'-'.$roundId;
            $rankClubKeySupportNum = 'rankCLub-supportNum-'.$paomeId.'-'.$roundId;
            $mileGameData = array(
                'type'=>1,
                'rank'=>($this->redis->zRevRank($rankClubJdKeyMile, $clubId)!== false) ? ($this->redis->zRevRank($rankClubJdKeyMile, $clubId)+1) : 0,
                'rankValue'=>($this->redis->zScore($rankClubJdKeyMile, $clubId)!== false) ? $this->redis->zScore($rankClubJdKeyMile, $clubId) : 0,
                'num'=>$this->redis->zSize($rankClubJdKeyMile) ? $this->redis->zSize($rankClubJdKeyMile) : 0
            );//里程
            $speedGameData = array(
                'type'=>2,
                'rank'=>($this->redis->zRank($rankClubKeySpeed, $clubId)!== false) ? ($this->redis->zRank($rankClubKeySpeed, $clubId)+1) : 0,
                'rankValue'=>($this->redis->zScore($rankClubKeySpeed, $clubId)!== false) ? common::sec3format($this->redis->zScore($rankClubKeySpeed, $clubId)) : 0,
                'num'=>$this->redis->zSize($rankClubKeySpeed) ? $this->redis->zSize($rankClubKeySpeed) : 0
            );//配速
            $supportGameData = array(
                'type'=>3,
                'rank'=>($this->redis->zRevRank($rankClubKeySupportNum, $clubId)!== false) ? ($this->redis->zRevRank($rankClubKeySupportNum, $clubId)+1) : 0,
                'rankValue'=>($this->redis->zScore($rankClubKeySupportNum, $clubId)!== false) ? $this->redis->zScore($rankClubKeySupportNum, $clubId) : 0,
                'num'=>$this->redis->zSize($rankClubKeySupportNum) ? $this->redis->zSize($rankClubKeySupportNum) : 0
            );//人气
        }
        $gameData[0] = $mileGameData;
        $gameData[1] = $speedGameData;
        $gameData[2] = $supportGameData;
        $result = array('gameTitle'=>$gameTitle,'gameData'=>$gameData);
        return $result;
    }

    /**
     * 用户跑步轮次记录
     * @param $paomeId
     * @param $clubId
     * @param $roundId 轮次ID
     * @return array
     */
    public function getUserRunLog2($paomeId, $clubId, $roundId) {
        $list = $this->paomeDb->getAll("select uid from r_pm_club_users
                                  where club_id=$clubId
                                  and status=0");
        if (!$list) {
            return array('gameNum'=>0,'list'=>[]);
        }
        $arrUid = [];
        foreach ($list as $key=>$val) {
            $arrUid[] = $val['uid'];
        }
        $strUid = implode(',', $arrUid);
        $arrDataList = $this->paomeDb->getAll("select uid,mileage,day_num,speed,support_num
                                      from r_pm_users_rounds
                                       where contest_id=$paomeId and club_id=$clubId
                                       and uid in($strUid) and type= $roundId");
        $arrData = [];
        if ($arrDataList) {
            foreach ($arrDataList as $k =>$v) {
                $arrData[$val['uid']]= $v;
            }
        }
        $result = [];
        foreach ($list as $key=>$val) {
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'nickname');
            $result[$key]['uid'] = $val['uid'];
            $result[$key]['header'] = $header;
            $result[$key]['nickname'] = $nickname;
            $result[$key]['mileage'] = ($arrData && isset($arrData[$val['uid']])) ? $arrData[$val['uid']]['mileage'] : 0;
            $result[$key]['dayNum'] = ($arrData && isset($arrData[$val['uid']])) ? $arrData[$val['uid']]['day_num'] : 0;
            $result[$key]['speed'] = ($arrData && isset($arrData[$val['uid']]) && ($arrData[$val['uid']]['speed'] > 0) ) ? common::sec3format($arrData[$val['uid']]['speed']) : 0;
            $result[$key]['supportNum'] = ($arrData && isset($arrData[$val['uid']])) ? $arrData[$val['uid']]['support_num'] : 0;
        }
        return array('gameNum'=>count($list),'list'=>$result);
    }
    public function getUserRunLog($paomeId, $clubId, $roundId) {
        $list = $this->paomeDb->getAll("select b.*,a.mileage,a.speed,a.support_num,a.day_num from r_pm_club_users as b
                                  left join r_pm_users_rounds as a on a.uid= b.uid
                                  where a.club_id=$clubId
                                  and a.contest_id=$paomeId
                                  and a.type=$roundId and b.club_id= $clubId and b.status=0");
        if (!$list) {
            return array(
                array('typeWd'=>1,'gameNum'=>0,'list'=>[]),
                array('typeWd'=>2,'gameNum'=>0,'list'=>[]),
                array('typeWd'=>3,'gameNum'=>0,'list'=>[])
            );
        }
        $mile = [];
        $speed = [];
        $support = [];

        $i = 0;
        $j =0;
        $m = 0;

        $mileSort = [];
        $speedSort = [];
        $supportSort = [];
        foreach ($list as $key=>$val) {
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'nickname');

            if ($val['mileage'] > 0) {
                $mile[$i]['uid'] = $val['uid'];
                $mile[$i]['header'] = $header;
                $mile[$i]['nickname'] = $nickname;
                $mile[$i]['rank'] = 0;
                $mile[$i]['rankValue'] = $val['mileage'];
                $mile[$i]['dayNum'] = $val['day_num'];
                $mileSort[] = $val['mileage'];
                $i++;
            }

            if ($val['speed'] > 0) {
                $speed[$j]['uid'] = $val['uid'];
                $speed[$j]['header'] = $header;
                $speed[$j]['nickname'] = $nickname;
                $speed[$j]['rank'] = 0;
                $formartSpeed = common::sec3format($val['speed']);
                $speed[$j]['rankValue'] = $formartSpeed;
                $speed[$j]['dayNum'] = $val['day_num'];
                $speedSort[] = $formartSpeed;
                $j++;
            }

            if ($val['support_num'] > 0) {
                $support[$m]['uid'] = $val['uid'];
                $support[$m]['header'] = $header;
                $support[$m]['nickname'] = $nickname;
                $support[$m]['rank'] = 0;
                $support[$m]['rankValue'] = $val['support_num'];
                $support[$m]['dayNum'] = $val['day_num'];
                $supportSort[] = $val['support_num'];
                $m++;
            }
        }

        if ($mile) {
            array_multisort($mileSort, SORT_DESC, $mile);
            foreach ($mile as $k =>$v) {
                $mile[$k]['rank'] = $k+1;
            }
        }
        if ($speed) {
            array_multisort($speedSort, SORT_ASC, $speed);
            foreach ($speed as $k =>$v) {
                $speed[$k]['rank'] = $k+1;
            }
        }
        if ($support) {
            array_multisort($supportSort, SORT_DESC, $support);
            foreach ($support as $k =>$v) {
                $support[$k]['rank'] = $k+1;
            }
        }
        return array(
            array('typeWd'=>1,'gameNum'=>count($mile),'list'=>$mile),
            array('typeWd'=>2,'gameNum'=>count($speed),'list'=>$speed),
            array('typeWd'=>3,'gameNum'=>count($support),'list'=>$support)
        );
    }

    /**
     * 争霸赛homedata成员每日数据
     */
    public function getUserRunLogNew($paomeId, $clubId, $roundId) {
        $roundId = 100;
        //查询战队所有成员
        $list = $this->paomeDb->getAll("select id,uid,`level` from r_pm_club_users where club_id=$clubId and status=0");
        if (!$list) {
            return array(
                array('typeWd'=>1,'gameNum'=>0,'list'=>[]),
                array('typeWd'=>2,'gameNum'=>0,'list'=>[]),
                array('typeWd'=>3,'gameNum'=>0,'list'=>[])
            );
        }

        $mile = [];
        $speed = [];
        $support = [];

        $mileSort = [];
        $speedSort = [];
        $supportSort = [];

        $i = 0;
        $j = 0;
        $m = 0;

        $arrDate = $this->base->load('paome/cup')->getDateList($paomeId, $roundId);
        $date = 0;
        if($arrDate){
            $date = $this->base->load('paome/cup')->getLastDate($arrDate);
        }

        $rankClubKeySupportNum = 'rankCLub-supportNum-'.$paomeId.'-'.$roundId;
        //查询战队成员数据
        foreach ($list as $key=>$val) {
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'nickname');
            $userCurrentDayMileage = 0;
            $intSec = cupModel::DEFAULT_SPEED_RANK_VALUE;//默认值，排除0配速干扰
            $userCurrentDaySpeed =  common::sec3format(0);
            if($date) {
                list($userCurrentDayMileage, $userCurrentDayElapsedtime) = $this->base->load('paome/cup')->getUserCurrentDayMileage($paomeId, $clubId, $val['uid'], $date);
                if($userCurrentDayElapsedtime >0) {
                    $intSec = $this->base->load('paome/cup')->getSecSpeed($userCurrentDayMileage, $userCurrentDayElapsedtime);
                    $userCurrentDaySpeed = common::sec3format($intSec);
                }
            }
            $mile[$key]['uid'] = $val['uid'];
            $mile[$key]['header'] = $header;
            $mile[$key]['nickname'] = $nickname;
            $mile[$key]['rank'] = 0;
            $mile[$key]['rankValue'] = $userCurrentDayMileage;
            $mileSort[] = $userCurrentDayMileage;
            $userCurrentDayMileage >0 && $i++;//实际有跑步数据的人++

            $speed[$key]['uid'] = $val['uid'];
            $speed[$key]['header'] = $header;
            $speed[$key]['nickname'] = $nickname;
            $speed[$key]['rank'] = 0;
            $speed[$key]['rankValue'] = $userCurrentDaySpeed;
            $speedSort[] = $intSec;
            $userCurrentDaySpeed >0 && $j++;//实际有跑步数据的人++

            $supportNum = $this->paomeDb->getOne("select support_num from r_pm_users_rounds where club_id=$clubId and contest_id=$paomeId and uid= {$val['uid']} and `type`=$roundId");
            $support[$key]['uid'] = $val['uid'];
            $support[$key]['header'] = $header;
            $support[$key]['nickname'] = $nickname;
            $support[$key]['rank'] = 0;
            $support[$key]['rankValue'] = $supportNum;
            $supportSort[] = $supportNum;
            $supportNum >0 && $m++;//实际有跑步数据的人++
        }

        //排序
        if ($mile) {
            array_multisort($mileSort, SORT_DESC, $mile);
            foreach ($mile as $k =>$v) {
                $mile[$k]['rank'] = $v['rankValue'] > 0 ? $k+1 : 0;
            }
        }
        if ($speed) {
            array_multisort($speedSort, SORT_ASC, $speed);
            foreach ($speed as $k =>$v) {
                $speed[$k]['rank'] =  $v['rankValue'] > 0 ? $k+1 : 0;
            }
        }
        if ($support) {
            array_multisort($supportSort, SORT_DESC, $support);
            foreach ($support as $k =>$v) {
                $support[$k]['rank'] =  $v['rankValue'] > 0 ? $k+1 : 0;
            }
        }
        return array(
            array('typeWd'=>1,'gameNum'=>$i,'list'=>$mile),
            array('typeWd'=>2,'gameNum'=>$j,'list'=>$speed),
            array('typeWd'=>3,'gameNum'=>$m,'list'=>$support)
        );
    }

    /**
     * 明星成员
     */
    public function getClubMemberList($paomeId, $roundId, $clubId) {
        //战队所有成员
        $arrUidTwo = $this->paomeDb->getAll("select uid from r_pm_club_users where club_id=$clubId and status=0");
        $maxMileUid       = 0;
        $maxOnceMileUid   = 0;
        $maxSupportNumUid = 0;
        $maxSpeedUid      = 0;
        if ($arrUidTwo) {
            $arrUid = [];
            foreach ($arrUidTwo as $key=>$val) {
                $arrUid[] = $val['uid'];
            }
            $strUid = implode(',', $arrUid);
            $maxMileUid = $this->paomeDb->getOne("select uid from r_pm_users_rounds where contest_id=$paomeId and club_id=$clubId and `type`=$roundId and uid in($strUid) order by mileage desc limit 1");
            $maxOnceMileUid = $this->paomeDb->getOne("select uid from r_pm_users_rounds where contest_id=$paomeId and club_id=$clubId and `type`=$roundId and uid in($strUid) order by max_mileage desc limit 1");
            $maxSupportNumUid = $this->paomeDb->getOne("select uid from r_pm_users_rounds where contest_id=$paomeId and club_id=$clubId and `type`=$roundId and uid in($strUid) order by support_num desc limit 1");
            $maxSpeedUid = $this->paomeDb->getOne("select uid from r_pm_users_rounds where contest_id=$paomeId and club_id=$clubId and `type`=$roundId and uid in($strUid) and speed>0 order by speed  asc limit 1");
        }

        $leadId = $this->paomeDb->getOne("select head_uid from r_pm_club where id=$clubId");
        $arrLeader = [];
        if ($leadId) {
            $arrLeader = array(
                'uid'=>$leadId,
                'header'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $leadId, 'header'),
                'nickname'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $leadId, 'nickname')
            );
        }

        $arrMaxMile = [];
        if ($maxMileUid) {
            $isInCLub = $this->getMemberIsInClub($maxMileUid);
            if($isInCLub) {
                $arrMaxMile = array(
                    'uid'=>$maxMileUid,
                    'header'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxMileUid, 'header'),
                    'nickname'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxMileUid, 'nickname')
                );
            }

        }

        $arrMaxOnceMile = [];
        if ($maxOnceMileUid) {
            $isInCLub = $this->getMemberIsInClub($maxOnceMileUid);
            if ($isInCLub) {
                $arrMaxOnceMile = array(
                    'uid'=>$maxOnceMileUid,
                    'header'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxOnceMileUid, 'header'),
                    'nickname'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxOnceMileUid, 'nickname')
                );
            }
        }

        $arrMaxSupportNumUid = [];
        if ($maxSupportNumUid) {
            $isInCLub = $this->getMemberIsInClub($maxSupportNumUid);
            if ($isInCLub) {
                $arrMaxSupportNumUid = array(
                    'uid'=>$maxSupportNumUid,
                    'header'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxSupportNumUid, 'header'),
                    'nickname'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxSupportNumUid, 'nickname')
                );
            }
        }
        $arrMaxSpeedUid = [];
        if ($maxSpeedUid) {
            $isInCLub = $this->getMemberIsInClub($maxSpeedUid);
            if ($isInCLub) {
                $arrMaxSpeedUid = array(
                    'uid'=>$maxSpeedUid,
                    'header'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxSpeedUid, 'header'),
                    'nickname'=>$this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxSpeedUid, 'nickname')
                );
            }
        }

        /*新增去重逻辑*/
        if ($roundId == 100) {
            $re = array_unique(array($leadId, $maxSupportNumUid, $maxSpeedUid));
            $uniqueArr =[];
            if (count($re) == 1) {
                $uniqueArr =  array(
                    'leader'=>$arrLeader,
                    'support'=>[],
                    'speed'=>[]
                );
            }else if(count($re) == 2) {
                if ($leadId == $maxSupportNumUid) {
                    $uniqueArr =  array(
                        'leader'=>$arrLeader,
                        'support'=>[],
                        'speed'=>$arrMaxSpeedUid
                    );
                } else {
                    $uniqueArr =  array(
                        'leader'=>$arrLeader,
                        'support'=>$arrMaxSupportNumUid,
                        'speed'=>[]
                    );
                }
            } else {
                $uniqueArr =  array(
                    'leader'=>$arrLeader,
                    'support'=>$arrMaxSupportNumUid,
                    'speed'=>$arrMaxSpeedUid
                );
            }
            return $uniqueArr;
        } else {
            return array(
                'leader'=>$arrLeader,
                'mile'=>$arrMaxMile,
                'onceMile'=>$arrMaxOnceMile,
                'support'=>$arrMaxSupportNumUid,
                'speed'=>$arrMaxSpeedUid
            );
        }


    }

    /**
     * 战队详情-图标chart数据
     */
    public function getClubChart($paomeId, $roundId, $clubId) {
        $arrList = [];
        $mile = [];
        $speed = [];
        $support = [];
        switch($roundId){
            case 1:
                $arrList = $this->paomeDb->getAll("select `type`,start_time from r_pm_rounds where contest_id=$paomeId and `type` in(5,11)");
                break;
            case 5:
                $arrList = $this->paomeDb->getAll("select `type`,start_time from r_pm_rounds where contest_id=$paomeId and `type` in(15,21)");
                break;
            case 10:
                $arrList = $this->paomeDb->getAll("select `type`,start_time from r_pm_rounds where contest_id=$paomeId and `type` in(25,31)");
                break;
            case 100:
                $arrList = $this->paomeDb->getAll("select `type`,start_time from r_pm_rounds where contest_id=$paomeId and `type` in(105,106)");
                break;
        }

        if (!$arrList) {
            return array('mile'=>$mile, 'speed'=>$speed, 'support'=>$support);
        }
        $startTime = 0;
        $endTime = 0;
        foreach ($arrList as $key=>$val) {
            if (in_array($val['type'], array(5,15,25,105))) {
                $startTime = strtotime(date("Ymd", $val['start_time']));
            } else {
                $endTime = (strtotime(date("Ymd")) >= strtotime(date("Ymd", $val['start_time']))) ? strtotime(date("Ymd", $val['start_time'])): strtotime(date("Ymd"));
            }
        }

        if($roundId == 100) {
            $total = $this->paomeDb->getOne("select count(1) from r_pm_score where contest_id=$paomeId and `type`=$roundId and score_rank_num>0");
            for($i=$startTime; $i<=$endTime; $i=$i+86400){
                $date = date('Ymd', $i);
                $rankNum = $this->base->load('paome/rank')->getObjectDayRank($clubId, $paomeId, $roundId, $date, 1);
                $rankValue = $this->base->load('paome/rank')->getObjectDayRankValue($clubId, $paomeId, $roundId, $date, 1);
                $mile[]= array(
                    'formatTime'=>date('Ymd', $i),
                    'rankValue'=>$rankValue,
                    'rank'=>$rankNum,
                    'num'=>$total,
                    'score'=>$this->base->load('paome/rank')->getClubRankScore((int)$rankNum, 1)
                );
                $rankNum = $this->base->load('paome/rank')->getObjectDayRank($clubId, $paomeId, $roundId, $date, 5);
                $rankValue = $this->base->load('paome/rank')->getObjectDayRankValue($clubId, $paomeId, $roundId, $date, 5);
                $speed[]= array(
                    'formatTime'=>date('Ymd', $i),
                    'rankValue'=>$rankValue,
                    'rank'=>$rankNum,
                    'num'=>$total,
                    'score'=>$this->base->load('paome/rank')->getClubRankScore((int)$rankNum, 5)
                );
                $rankNum = $this->base->load('paome/rank')->getObjectDayRank($clubId, $paomeId, $roundId, $date, 10);
                $rankValue = $this->base->load('paome/rank')->getObjectDayRankValue($clubId, $paomeId, $roundId, $date, 10);
                $support[]= array(
                    'formatTime'=>date('Ymd', $i),
                    'rankValue'=>$rankValue,
                    'rank'=>$rankNum,
                    'num'=>$total,
                    'score'=>$this->base->load('paome/rank')->getClubRankScore((int)$rankNum, 10)
                );
            }
        } else {
            for($i=$startTime; $i<=$endTime; $i=$i+86400){
                $rankClubDayKeyMile = 'rankClubDay-mileage-'.$paomeId.'-'.$roundId.'-'.date('Y-m-d', $i);//天
                $mile[]= array(
                    'formatTime'=>date('Ymd', $i),
                    'rankValue'=>($this->redis->zScore($rankClubDayKeyMile, $clubId) !== false) ? $this->redis->zScore($rankClubDayKeyMile, $clubId) : 0,
                    'rank'=>($this->redis->zRevRank($rankClubDayKeyMile, $clubId) !== false) ? $this->redis->zRevRank($rankClubDayKeyMile, $clubId)+1 : 0,
                    'num'=>($this->redis->zSize($rankClubDayKeyMile)!==false) ? $this->redis->zSize($rankClubDayKeyMile) : 0
                );
                $rankClubDayKeySpeed = 'rankClubDay-speed-'.$paomeId.'-'.$roundId.'-'.date('Y-m-d',$i);//天
                $speed[]= array(
                    'formatTime'=>date('Ymd', $i),
                    'rankValue'=>($this->redis->zScore($rankClubDayKeySpeed, $clubId) !== false) ? common::sec3format($this->redis->zScore($rankClubDayKeySpeed, $clubId)) : 0,
                    'rank'=>($this->redis->zRank($rankClubDayKeySpeed, $clubId) !== false) ? $this->redis->zRevRank($rankClubDayKeySpeed, $clubId)+1 : 0,
                    'num'=>($this->redis->zSize($rankClubDayKeySpeed)!==false) ? $this->redis->zSize($rankClubDayKeySpeed) : 0
                );
                $rankClubDayKeySupportNum = 'rankClubDay-supportNum-'.$paomeId.'-'.$roundId.'-'.date('Y-m-d', $i);//天
                $support[]= array(
                    'formatTime'=>date('Ymd', $i),
                    'rankValue'=>($this->redis->zScore($rankClubDayKeySupportNum, $clubId) !== false) ? $this->redis->zScore($rankClubDayKeySupportNum, $clubId) : 0,
                    'rank'=>($this->redis->zRevRank($rankClubDayKeySupportNum, $clubId) !== false) ? $this->redis->zRevRank($rankClubDayKeySupportNum, $clubId)+1 : 0,
                    'num'=>($this->redis->zSize($rankClubDayKeySupportNum)!==false) ? $this->redis->zSize($rankClubDayKeySupportNum) : 0
                );
            }
        }

        return array('mile'=>$mile, 'speed'=>$speed, 'support'=>$support);
    }

    /**
     * 查询当前用户战队+前后各一轮战队 数据，app 首页需要
     */
    public function getUserClubNextPreList($uid) {
        $myClubInfo = $this->getUserCurrentClubInfo($uid);
        if (!$myClubInfo) return [];
        $arrPaome =  $this->base->load('paome/cup')->getCurrentPaomeInfo('id,status');
        if (!$arrPaome) {
            return [];
        }
        $paomeId = $arrPaome['id'];
        $roundsDict = common::$roundsDict;
        $roundId = 1;
        foreach ($roundsDict as $k =>$v) {
            if (in_array($arrPaome['status'],$v)) {
                $roundId = $k;
                break;
            }
        }
        $nowTime = time();
        $yesterdayTime = time()-86400;
        $rankClubKeyMile = 'rankClub-mileage-'.$paomeId.'-'.$roundId;//页面展示排名
        $rankClubDayKeyMileYd = 'rankClubDay-mileage-'.$paomeId.'-'.$roundId.'-'.date('Y-m-d',$yesterdayTime);//天
        $rankClubDayKeyMileTd = 'rankClubDay-mileage-'.$paomeId.'-'.$roundId.'-'.date('Y-m-d',$nowTime);//今天
        //总排名
        $rank  = ($this->redis->zRevRank($rankClubKeyMile, $myClubInfo['id']) !== false) ? $this->redis->zRevRank($rankClubKeyMile, $myClubInfo['id'])+1 : 0;
        if (!$rank) {
            return [];
        }
        $image = $myClubInfo['image'] ? $myClubInfo['image'].'?imageView2/2/w/128/h/128' : '';
        $title = $myClubInfo['title'] ;
        $mileTd = ($this->redis->zScore($rankClubDayKeyMileTd, $myClubInfo['id']) !== false) ? $this->redis->zScore($rankClubDayKeyMileTd, $myClubInfo['id']) : 0;
        $mileYd = ($this->redis->zScore($rankClubDayKeyMileYd, $myClubInfo['id']) !==false) ? $this->redis->zScore($rankClubDayKeyMileYd, $myClubInfo['id']) : 0;
        $intInc = bcsub($mileTd, $mileYd,2) < 0 ? 0 : bcsub($mileTd, $mileYd,2); //今日新增
        $mile = ($this->redis->zScore($rankClubKeyMile, $myClubInfo['id']) !==false) ? $this->redis->zScore($rankClubKeyMile, $myClubInfo['id']) : 0 ;
        $num = $this->redis->zSize($rankClubKeyMile);//排名总人数
        $rankToday = ($this->redis->zRevRank($rankClubDayKeyMileTd, $myClubInfo['id']) !==false) ? $this->redis->zRevRank($rankClubDayKeyMileTd, $myClubInfo['id'])+1 : 0;
        $rankYes = ($this->redis->zRevRank($rankClubDayKeyMileYd, $myClubInfo['id']) !== false) ? $this->redis->zRevRank($rankClubDayKeyMileYd, $myClubInfo['id'])+1 : 0;
        if ($rankYes) {
            $num2 = bcsub($rankYes, $rankToday);
            $changeDesc = $this->base->load('paome/rank')->drawChangeDescForRank($num2);
        } else {
            $changeDesc = [];
        }
        $arrCurrent = array(
            'clubId'=>$myClubInfo['id'],
            'rank'=>$rank,
            'title'=>$title,
            'image'=>$image,
            'tdInc'=>$intInc,
            'mile'=>$mile,
            'num'=>$num,
            'changeDesc'=>$changeDesc
        );

        //前一名战队
        $preClub = [];
        $arrRankList = $this->redis->zRevRange($rankClubKeyMile, 0 , -1);
        if ($rank > 1) {
            $preKey = $rank-2;//上一轮redis 的下标
            $preId = isset($arrRankList[$preKey]) ? $arrRankList[$preKey] : 0;
            if ($preId) {
                $preClubInfo = $this->getClubInfo($preId);
               if ($preClubInfo) {
                   //总排名
                   $rankPre  = ($this->redis->zRevRank($rankClubKeyMile, $preClubInfo['id']) !== false) ? $this->redis->zRevRank($rankClubKeyMile, $preClubInfo['id'])+1 : 0;
                   if ($rankPre) {
                       $image = $preClubInfo['image'] ? $preClubInfo['image'].'?imageView2/2/w/128/h/128' : '';
                       $title = $preClubInfo['title'] ;
                       $mileTd = ($this->redis->zScore($rankClubDayKeyMileTd, $preClubInfo['id']) !== false) ? $this->redis->zScore($rankClubDayKeyMileTd, $preClubInfo['id']) : 0;
                       $mileYd = ($this->redis->zScore($rankClubDayKeyMileYd, $preClubInfo['id']) !==false) ? $this->redis->zScore($rankClubDayKeyMileYd, $preClubInfo['id']) : 0;
                       $intInc = bcsub($mileTd, $mileYd,2) < 0 ? 0 : bcsub($mileTd, $mileYd,2); //今日新增
                       $mile = ($this->redis->zScore($rankClubKeyMile, $preClubInfo['id']) !==false) ? $this->redis->zScore($rankClubKeyMile, $preClubInfo['id']) : 0 ;
                       $num = $this->redis->zSize($rankClubKeyMile);//排名总人数
                       $rankToday = ($this->redis->zRevRank($rankClubDayKeyMileTd, $preClubInfo['id']) !==false) ? $this->redis->zRevRank($rankClubDayKeyMileTd, $preClubInfo['id'])+1 : 0;
                       $rankYes = ($this->redis->zRevRank($rankClubDayKeyMileYd, $preClubInfo['id']) !== false) ? $this->redis->zRevRank($rankClubDayKeyMileYd, $preClubInfo['id'])+1 : 0;
                       if($rankYes) {
                           $num2 = bcsub($rankYes, $rankToday);
                           $changeDesc = $this->base->load('paome/rank')->drawChangeDescForRank($num2);
                       } else {
                           $changeDesc = [];
                       }

                       //该俱乐部内最远用户信息
                       $maxUser = $this->base->load('paome/home')->getMaxUserInClub($preId, $paomeId, $roundId);
                       $preClub = array(
                           'clubId'=>$preClubInfo['id'],
                           'rank'=>$rankPre,
                           'title'=>$title,
                           'image'=>$image,
                           'tdInc'=>$intInc,
                           'mile'=>$mile,
                           'num'=>$num,
                           'changeDesc'=>$changeDesc,
                           'maxUser'=>$maxUser
                       );
                   }
               }
            }
        }
        //后一名战队
        $nextClub =[];
        if ($rank < count($arrRankList)) {
            $nexKey = $rank;//下一轮redis 的下标
            $nextId = isset($arrRankList[$nexKey]) ? $arrRankList[$nexKey] : 0;
            if ($nextId) {
                $nextClubInfo = $this->getClubInfo($nextId);
                if ($nextClubInfo) {
                    //总排名
                    $rankNext  = ($this->redis->zRevRank($rankClubKeyMile, $nextClubInfo['id']) !== false) ? $this->redis->zRevRank($rankClubKeyMile, $nextClubInfo['id'])+1 : 0;
                    if ($rankNext) {
                        $image = $nextClubInfo['image'] ? $nextClubInfo['image'].'?imageView2/2/w/128/h/128' : '';
                        $title = $nextClubInfo['title'] ;
                        $mileTd = ($this->redis->zScore($rankClubDayKeyMileTd, $nextClubInfo['id']) !== false) ? $this->redis->zScore($rankClubDayKeyMileTd, $nextClubInfo['id']) : 0;
                        $mileYd = ($this->redis->zScore($rankClubDayKeyMileYd, $nextClubInfo['id']) !==false) ? $this->redis->zScore($rankClubDayKeyMileYd, $nextClubInfo['id']) : 0;
                        $intInc = bcsub($mileTd, $mileYd,2) < 0 ? 0 : bcsub($mileTd, $mileYd,2); //今日新增
                        $mile = ($this->redis->zScore($rankClubKeyMile, $nextClubInfo['id']) !==false) ? $this->redis->zScore($rankClubKeyMile, $nextClubInfo['id']) : 0 ;
                        $num = $this->redis->zSize($rankClubKeyMile);//排名总人数
                        $rankToday = ($this->redis->zRevRank($rankClubDayKeyMileTd, $nextClubInfo['id']) !==false) ? $this->redis->zRevRank($rankClubDayKeyMileTd, $nextClubInfo['id'])+1 : 0;
                        $rankYes = ($this->redis->zRevRank($rankClubDayKeyMileYd, $nextClubInfo['id']) !== false) ? $this->redis->zRevRank($rankClubDayKeyMileYd, $nextClubInfo['id'])+1 : 0;
                        if($rankYes) {
                            $num2 = bcsub($rankYes, $rankToday);
                            $changeDesc = $this->base->load('paome/rank')->drawChangeDescForRank($num2);
                        } else {
                            $changeDesc = [];
                        }

                        //该俱乐部内最远用户信息
                       $maxUser = $this->base->load('paome/home')->getMaxUserInClub($nextId, $paomeId, $roundId);
                        $nextClub = array(
                            'clubId'=>$nextClubInfo['id'],
                            'rank'=>$rankNext,
                            'title'=>$title,
                            'image'=>$image,
                            'tdInc'=>$intInc,
                            'mile'=>$mile,
                            'num'=>$num,
                            'changeDesc'=>$changeDesc,
                            'maxUser'=>$maxUser
                        );
                    }
                }
            }
        }
        $result = [];
        if ($preClub && $arrCurrent) {
            $arrCurrent['preDiff'] = $preClub['mile'] - $arrCurrent['mile'];
        }
        if ($nextClub && $arrCurrent) {
            $arrCurrent['nextDiff'] = $arrCurrent['mile'] - $nextClub['mile'];
        }
        if ($preClub) {
            $result['preClub'] = $preClub;
        }
        if ($arrCurrent) {
            $result['currentClub'] = $arrCurrent;
        }
        if ($nextClub) {
            $result['nextClub'] = $nextClub;
        }
         return $result;
    }

    /**
     * 战队证书
     */
    public function getClubCertificate($paomeId, $clubId) {
        $sql = "select * from r_pm_certificate where contest_id = {$paomeId} and club_id = {$clubId} order by create_time desc";
        return $this->paomeDb->getAll($sql);
    }

    /**
     * 发证书
     * @param $paomeId 赛季ID
     * @param $clubId  战队ID
     * @param $roundId 轮次ID
     * @param $typeWd  维度
     * @param $rank 排名
     * @param $rankValue 排名值
     * @param int $mileageScore 积分
     * @param int $speedScore
     * @param int $supportScore
     * @return mixed
     */
    public function sendCertificateToClub($paomeId, $clubId, $roundId, $typeWd, $rank, $rankValue, $mileageScore=0, $speedScore=0, $supportScore=0) {
        $data = array(
            'contest_id'=>$paomeId,
            'type'=>$roundId,
            'club_id'=>$clubId,
            'type_wd'=>$typeWd,
            'rank_num'=>$rank,
            'create_time'=>time(),
            'rank_value'=>$rankValue,
            'mileage_score'=>$mileageScore,
            'speed_score'=>$speedScore,
            'support_score'=>$supportScore
        );
        return $this->paomeDb->insertRow('r_pm_certificate',$data,mysqldb::INSERT_COMMON);
    }
}